作者:心在流血谁懂 | 来源:互联网 | 2023-05-26 15:36
放在jsfiddle上的角度代码是关于一个自定义指令,它使用$compile($element)($scope)
并导致ng-click操作发生两次:我的问题是:
我想了解,为什么ng-click动作会发生两次?
打电话的目的是$compile($element)($scope)
什么?
如果没有被调用会发生什么,在什么情况下应该调用?
以下是我到目前为止收集的细节和内容:
我想了解,为什么ng-click动作会发生两次?以下行显示自定义指令"hello"并按下按钮.自定义指令调用$compile($element)($scope)
,这是导致操作被触发两次的行,但我不明白如何?
测试点击!
这是代码 - http://jsfiddle.net/4x4L3gtw/27/
var myApp = angular.module('myApp', []);
myApp.controller('DirectiveTestController', ['$scope',
function ($scope) {
$scope.testClick = function () {
window.alert("hey");
console.log("hey");
}
}]);
myApp.directive('hello', function () {
return {
scope: true,
controller: ['$scope', '$element', '$compile', function ($scope, $element, $compile) {
$element.removeAttr('hello');
// $element.removeAttr('ng-click');
$compile($element)($scope);
}]
};
});
调用的目的是$compile($element)($scope)
什么,如果没有调用会发生什么,在什么情况下应该调用它?
(点击按钮,你会发现动作发生了两次)
该指令的目的是基于某些逻辑隐藏/禁用.所以在这个指令中我看到$element.removeAttr("ng-hide")
等等,每次$element.removeAttr
调用它后跟一个$compile($element)($scope)
,是重写DOM的目的吗?
我检查了DOM,但是我没有看到多次定义ng-click.在检查DOM(firebug)时,我查看了$ element-> 0-> attributes-> ng-click(以及其他元素).
如果我删除ng-click使用,$element.removeAttr("ng-click")
则该操作仅发生一次.或者,如果我删除该$compile($element)($scope)
操作只发生一次.