簡體   English   中英

在angular-js中的指令的鏈接函數中編寫指令

[英]Writing directives in the link function of a directive in angular-js

我在angular.js中定義了一個指令。 該指令具有鏈接功能和控制器功能,並且沒有模板,因此所有視圖都在鏈接功能中生成。 在鏈接功能中,我正在執行以下操作:

var button=angular.element("<a>");
button.addClass("ng-click: previousLink();");

//previousLink() is a function defined in the scope.
//I am doing it like that, because before that one I attempted to do:
//button.prop("ng-click", "previousLink()");
//button.text("Previous");
//but for some reason it was showing on html as <a>Next</a>, without adding the property.

這是行不通的。 如果我單擊該按鈕,則無濟於事。 如果不是使用代碼在鏈接功能中執行此操作,而是使用模板,則可以使用。 由於某些原因,我需要在鏈接函數中使用jquery進行一些操作。 我該怎么辦? 無論如何,還是要使這項工作有效,還是我必須同時使用模板和鏈接功能,並在那里進行組合?

要使用$compile您需要使用類似以下內容的現有代碼:

$compile(button.contents())(scope);

如果您希望它是動態的,可以將其放在$watch如下所示:

link: function (scope, ele, attrs) {
  scope.$watch(attrs.yourval, function(html) {
    var button=angular.element("<a>");
    button.addClass("ng-click: previousLink();");
    $compile(button.contents())(scope);
  });
}

$compile將范圍(作為參數提供)附加到您定義的html。 這將使您的按鈕單擊正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM