[英]AngularJS Direcitve - link function doesn't fire
我想要實現的目標:將cordova原生處理程序包含在angular指令中
我想使用指令包裝器為Cordova的本機事件實現處理程序(以便監聽body load事件)。
我有以下指令樣板:
angular.module('vitaApp')
.directive('cordovaNative', function () {
return {
restrict: 'A',
compile: function (element, attrs, transcludeFn) {
alert('compile fired');
element.bind('load', function(){
alert('load occured');
});
},
link: function postLink(scope, element, attrs) {
alert('link fired');
element.bind('load', function(){
alert('load occured');
});
}
};
});
以下列方式實例化:
<body ng-app="vitaApp" ng-controller="metaCtrl" ng-swipe-right="showMenu()" ng-swipe-left="hideMenu()" cordova-native>
編譯cordovaNative指令的函數會觸發,但鏈接函數卻沒有。
它可能與ng-swipe指令有關(例如'{terminal:true}')?
注意:我不是試圖一起使用compile
和link
,我試圖證明它們不是為了單獨訂閱load
事件而工作。
您不能在指令中同時具有編譯和鏈接功能。 如果使用編譯,則應返回一個函數,該函數本身就是一個鏈接函數。 所以上面的代碼變成:
compile: function (elem, attrs, transcludeFn) {
alert('compile fired');
return function(scope, element, attrs) {
alert('link fired');
element.on('load', function(){
alert('load occured');
});
}
},
更新 :由於指令鏈接函數在加載元素后運行(大多數情況下),可能不需要在指令鏈接函數內添加element load
事件處理程序。
來自Angular Docs:
link
This property is used only if the compile property is not defined.
由於您定義了編譯功能,因此不需要鏈接功能。 這里有更多相關信息。
如果未定義編譯函數,則只應使用鏈接函數。 因此,在您的情況下,因為定義了編譯函數,您必須返回postLink函數或具有preLink和postLink函數的對象。
.directive('cordovaNative', function () {
return {
restrict: 'A',
compile: function (elem, attrs, transcludeFn) {
return {
pre: function preLink() {
alert('Pre link');
},
post: function postLink(scope, element, attrs) {
alert('link fired');
element.bind('load', function(){
alert('load occured');
});
}
}
}
};
});
或者,如果您不需要preLink功能:
.directive('cordovaNative', function () {
return {
restrict: 'A',
compile: function (elem, attrs, transcludeFn) {
return function postLink(scope, element, attrs) {
alert('link fired');
element.bind('load', function(){
alert('load occured');
});
}
}
};
});
這是一個小提琴 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.