我尝试通过指令向元素添加动画。动画完成后,我希望它调用传递的回调函数。我尝试以这种方式实现它 ( SO - How to add validation attributes in an angularjs directive )
“addAnimation”指令:
angular.module('myModule')
.directive('addAnimation', function ($compile) {
return {
restrict: 'A',
scope: {
onFinish:"&"
},
replace: false,
terminal: true,
priority: 1000,
link: function (scope, element, attrs) {
element.on('click', function() {
$('.selector').animate({ ... }), function() {
if(attrs.cb) {
attrs.cb.onFinish();
}
});
})
element.removeAttr("addAnimation"); //remove the attribute to avoid indefinite loop
$compile(element)(scope);
}
};
});
应将动画添加到指令“aDirective”:
angular.module('myModule')
.directive('aDirective', function () {
return {
templateUrl: 'path/to/template.html',
restrict: 'EA',
link: function (scope, element, attrs) {
scope.test = function() {
console.log('this should be logged');
}
}
};
});
<div>
<div add-animation cb="{onFinish: 'test'}"></div>
</div>
当我点击它时,动画开始,但随后出现错误:
Uncaught TypeError: attrs.cb.onFinish is not a function
记录 attrs.cb
似乎没有解析函数:
{onFinish: 'test'}
我在这里做错了什么?
最佳答案
你已经在指令的范围内定义了onFinish
,你应该像在范围内一样使用它,它需要在元素中用作on-finish
,所以而不是:
attrs.cb.onFinish()
做
scope.onFinish()
另外,如果你这样定义它:
scope: {
onFinish:"&"
},
您应该以这种方式将其传递到指令中:
<div add-animation on-finish="test()"></div>
关于angularjs - 将回调传递给指令 - angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30850320/