2013-05-04 56 views
7

我在Angularjs上編寫了一個非常複雜的應用程序。這已經足夠讓我迷惑了。我更深入地研究Angular,並且看到我的代碼很糟糕。 我理解這個概念:AngularJS指令:編譯模板和監視範圍

module.directive('createControl', function($compile, $timeout){ 
    scope: { 
      // scope bindings with '=' & '@' 
      },                             
    template: '<div>Template string with binded {{ variables }}</div>',   
    link: function(scope, element, attrs){ 
      // Function with logic. Should watch scope. 
      } 

我有幾個問題:

  • 我的模板是複雜的,我有打算在鏈接功能動態
  • 我需要追加編譯模板模板的一部分元素,而不是取代。
  • 隨着概念上面我的模板,沒有任何插值追加...

所以我的代碼看起來像,在簡化圖:

module.directive('createControl', function($compile, $timeout){ 
    scope: { 
       var1: '@var1', 
       var2: '@var2', 
       var3: '@var3' 
      },                             
    template: '<div>{{ var1 }} {{ var3 }}</div>',   
    link: function(scope, element, attrs){ 
       $('.someelement').on('event', function(){ 
       var2 = 'SNIPPET'; // Need to watch it 
       }); 
       var3 = '<span>{{ var2 }}</span>'; 
      } 
    }) 

我的問題是:

如何用範圍變量編譯我的模板?

如何觀察範圍變量?

我是否應該將指令拆分爲兩個?如果我應該如何正確地做到這一點?

+0

如果願意使用角1.4,template'加入用於'函數,它允許訪問屬性http://code.angularjs.org/1.1.4/ docs/guide/directive – charlietfl 2013-05-04 15:52:59

+0

@charlietfl,你能否以你的評論作爲迴應的代碼示例? – I159 2013-05-05 12:30:28

+1

我錯了,還是你可以避免使用jQuery混合角? – Ismael 2013-07-18 11:52:09

回答

3

我想通過改變你的指令:

module.directive('createControl', function($compile, $timeout){ 
    scope: { 
       var1: '=var1', 
       var2: '=var2', 
       var3: '=var3' 
      },                             
    template: '<div>{{var1}} {{var3}}</div>',   
    link: function(scope, element, attrs){ 
       $('.someelement').on('event', function(){ 
       scope.var2 = 'SNIPPET'; // Need to watch it 
       }); 
       /*I do not see what you want to do*/ 
       scope.var3 = $compile('<span>{{var2}}</span>')(scope); 
      } 
    }) 
10

角1.1.4在過去幾周公布的補充能力template訪問屬性的指令:

例子:

app.directive('mytest',function(){ 
    return { 
    restrict:'E',  
    template:function(elem,attrs){  
     return '<div>'+attrs.a+' '+attrs.b+'</div>'; 
    } 
    } 
}); 
<mytest a="Hello" b="World"></mytest> 

DEMO

參見directive docs for version 1.1.4

+0

請注意,如果我有與OP相同的問題,但這只是爲我節省了一大堆時間感謝張貼。 – CallumD 2013-05-16 13:26:41

+1

只是想我會指出,你爲文檔添加的鏈接不能直接鏈接到任何原因。你必須去[這裏](http://code.angularjs.org/1.1.4/docs/api),然後在右上角搜索'指令'。 – forrestranger 2013-06-21 13:28:09