[英]How to define an angular directive inside an angular directive's link function?
[英]Use $compile inside Angular link function AND access directive arguements
我正在angular.js 1.x中創建指令
我將指令稱為:
<mydirective dirarg={{value-1}}></mydirective>
我想通過在指令的鏈接函數中放置用於操作DOM的代碼來創建指令。 鏈接函數生成的DOM的結構取決於dirarg的值,我希望某些元素具有ng-click屬性。
通過執行以下操作,我設法使ng-clicks起作用:
app.directive('calendar',function($compile){
return{
link: function(scope, element, attributes){
element.append($compile("<button ng-click='testt()'>hi</button>")(scope));
}
}
});
當我單擊該指令生成的按鈕時,函數testt()
運行。 但是,如果我嘗試訪問dirarg
,對testt()的調用將中斷。
app.directive('calendar',function($compile){
return{
scope:{
dirarg: '@'
},
link: function(scope, element, attributes){
element.append($compile("<button ng-click='testt()'>"+scope.dirarg+"</button>")(scope));
}
}
});
現在,此代碼使用dirarg填充按鈕的文本,但是ng-click功能中斷。 有人知道我如何才能同時執行ng-click和訪問指令的參數嗎?
明確地說,此按鈕只是一個示例。 我的實際情況比一個按鈕要復雜得多,所以不要告訴我更好的方法來制作有角度的按鈕。
當將范圍屬性添加到指令選項時,它使指令成為隔離的范圍,您也需要在指令內部傳遞testt函數,或在指令鏈接函數內部定義testt函數
<mydirective dirarg={{value-1}} testt="testt"></mydirective>
app.directive('calendar',function($compile){
return{
scope:{
dirarg: '@',
testt: '='
},
link: function(scope, element, attributes){
element.append($compile("<button ng-click='testt()'>"+scope.dirarg+"</button>")(scope));
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.