我尝试通过指令向元素添加动画。动画完成后,我希望它调用传递的回调函数。我尝试以这种方式实现它(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'}
我在这里做错了什么?
答案 0 :(得分:2)
你已经在指令范围内定义了onFinish
,你应该像使用范围一样使用它。它需要在元素中用作on-finish
,所以代替:
attrs.cb.onFinish()
DO
scope.onFinish()
另外,如果你这样定义:
scope: {
onFinish:"&"
},
你应该以这种方式将它传递给指令:
<div add-animation on-finish="test()"></div>