Basically, I created a directive that passes a promise to the link function from ng-click and and detects when the promise is done so that I can attach a class to it.
基本上,我创建了一个指令,它通过ng-click传递对链接函数的承诺,并检测承诺何时完成,以便我可以附加一个类。
Example:
.directive('myDirective', function($parse) {
return {
restrict: 'A',
scope: {
ng-click: '&'
},
link: function(scope) {
var d = $parse(scope.ngClick);
element.on('click', function(event) {
d().then(function() {
element.addClass(attrs.myDirective);
});
});
}
};
});
<element ng-click="promise();" my-directive="class"></element>
//controller function
$scope.promise = function() {
return promise().then(function() {});
}
It is doing what I want except that the controller function is getting called three times. I would really like to just use require: '^ngClick' here but since the ngClick directive does not have any controllers, I can't do that. Can anyone point me in the right direction? Thanks!
它正在做我想要的,除了控制器功能被调用三次。我真的很想在这里使用require:'^ ngClick',但由于ngClick指令没有任何控制器,我不能这样做。谁能指出我正确的方向?谢谢!
1 个解决方案
#1
Added event.preventDefault() to the event.on('click') function in the link of my directive:
将event.preventDefault()添加到我的指令链接中的event.on('click')函数:
element.on('click', function(event) {
event.preventDefault();
d().then(function() {
element.addClass(attrs.myDirective);
});
});
#1
Added event.preventDefault() to the event.on('click') function in the link of my directive:
将event.preventDefault()添加到我的指令链接中的event.on('click')函数:
element.on('click', function(event) {
event.preventDefault();
d().then(function() {
element.addClass(attrs.myDirective);
});
});