簡體   English   中英

angular.js:使用指令將另一個指令作為屬性插入

[英]angular.js: using a directive to insert another directive as an attribute

例如, UI Bootstrap有一個名為'typeahead'的指令,它建議字段的值。 假設我想制作一個指令,我可以將其用作元素的屬性,這將導致為該元素建議顏色。

這是一次失敗的嘗試......

指示:

angular.module('myApp')
  .directive('suggestcolors', function () {
    return {
      compile: function compile(element, attrs) {
        attrs.$set("typeahead", "color for color in ['red', 'blue', 'green']");
      }
    };
  });

視圖:

<textarea ng-model="foo" suggestcolors></textarea>

當我檢查textarea時,屬性已設置,但它沒有做任何事情。 如果我將更改移動到鏈接功能,也會發生同樣的事情。 直接在視圖中設置typeahead屬性按預期工作:

<textarea ng-model="foo" typeahead="color for color in ['red', 'blue', 'green']"></textarea>

(但我希望能夠動態插入此屬性,原因是DRY。我的實際用例比這更復雜。)

這里提出一個類似的問題(關於在編譯步驟中動態添加ng-click行為),但從未直接回答。

編譯之后,AngularJS只為所有子元素調用$compile 元素本身不會自動重新編譯,因此在此階段添加指令將不起作用。 在您的情況下,我認為您可以將它從編譯函數更改為鏈接函數(因此您獲得scope參數),並自己調用$compile(element)(scope)

看到這個小提琴 ,我有一個指令,添加style="color: red" ,另一個指令“動態”添加該指令。 除非我之后調用$compile ,否則它不起作用。

HTH!

暫無
暫無

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

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