【发布时间】:2015-08-31 06:04:00
【问题描述】:
我尝试通过指令向元素添加动画。动画完成后,我希望它调用传递的回调函数。我尝试以这种方式实现它 (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'}
我在这里做错了什么?
【问题讨论】:
标签: angularjs angularjs-directive