【发布时间】:2018-12-11 02:05:52
【问题描述】:
我使用this directive 来防止双击。
我的代码:
export function cbOneClickOnly($parse, $compile): ng.IDirective {
"use strict";
return {
compile: function(tElement: ng.IAugmentedJQuery, tAttrs: ng.IAttributes) {
if (tAttrs.ngClick) {
throw "Cannot have both ng-click and cb-one-click-only on an element";
}
tElement.attr("ng-click", "oneClick($event)");
tElement.attr("ng-dblclick", "dblClickStopper($event)");
tElement.removeAttr("cb-one-click-only");
let theClickFunctionToRun = $parse(tAttrs["cbOneClickOnly"]);
return {
pre: function(scope: ng.IScope, iElement: ng.IAugmentedJQuery) {
let hasBeenClicked: boolean = false;
scope.oneClick = function(event: Event) {
if (hasBeenClicked) {
throw "Already clicked";
}
hasBeenClicked = true;
$(event.srcElement).attr("disabled", "disabled");
theClickFunctionToRun(scope, { $event: event });
return true;
};
scope.dblClickStopper = function(event: Event) {
event.preventDefault();
throw "Double click not allowed!";
};
$compile(iElement)(scope);
}
};
},
restrict: "A",
scope: true
};
}
然后像这样添加到应用程序中:
angular.module(moduleId, []).directive("cbOneClickOnly", ["$parse", "$compile", cbOneClickOnly])
并像这样使用:
<md-button class="md-accent" cb-one-click-only="$ctrl.itemSaveClicked(item)">
Save
</md-button>
但我收到此错误:
> Error: [ngTransclude:orphan] Illegal use of ngTransclude directive in
> the template! No parent directive that requires a transclusion found.
> Element: <!-- ngIf: $ctrl.isSaveDisplayed() -->
> https://errors.angularjs.org/1.7.5/ngTransclude/orphan?p0=%3C!--%20ngIf%3A%20%24ctrl.isSaveDisplayed()%20--%3E
> at eval (angular.js:138)
> at Object.ngTranscludePostLink (angular.js:34687)
> at eval (angular.js:1365)
> at invokeLinkFn (angular.js:11235)
> at nodeLinkFn (angular.js:10554)
> at compositeLinkFn (angular.js:9801)
> at publicLinkFn (angular.js:9666)
> at lazyCompilation (angular.js:10080)
> at boundTranscludeFn (angular.js:9844)
> at controllersBoundTransclude (angular.js:10604) "<!-- ngIf: $ctrl.isSaveDisplayed() -->"
This solution 解决了我的问题,但在一个有 html 的指令上,而我的没有。
我像这样手动删除了ng-transclude:iElement.removeAttr("ng-transclude");,这导致按钮内的文本消失了。
这种没有模板的指令风格有什么解决办法?
【问题讨论】:
标签: angularjs angular-directive angularjs-ng-transclude