2014-03-28 129 views
2

我想更好地理解AngularJS如何編譯指令並更新視圖。AngularJS如何編譯指令?

這是我的具體問題。我有一個指令,像這樣:

angular.module('directives', []) 

.directive('test', function() { 
    return { 
     restrict: 'AE', 
     scope : { foo : '=' }, 
     template: '<div id={{foo.id}}>{{foo.data}}</div>' 
     link: function(scope, element, attrs) { 
      document.getElementById(scope.foo.id); /*1*/ 
     } 
    } 
}); 

在點1 scope.foo.iddefined。但是,該指令的模板尚未編譯,因此div ID未設置,並且getElementById返回null。一旦頁面完全呈現,並且我查看編譯後的模板,所有模板ID都已成功設置爲foo.id

我在這裏丟失了什麼?

重要的是要注意,對於我的特殊情況,我需要通過它的id明確地與模板div進行交互。

編輯:增加了一個小提琴:http://jsfiddle.net/6c4nb/8/

+0

問題,它說你需要與模板互動,你想用這個模板做的任何細節? – Pete

+0

我試圖初始化一個插件,明確需要傳入元素ID的元素。 – Dan

+0

你可以把它扔進小提琴嗎?如果沒有html和完整的js,你很難完全理解你在做什麼。 –

回答

3

好了,在有限的信息,我能得到你的工作的元素。我不完全確定你想要做什麼,但是你需要在指令中設置元素的id。

如果有更好理解的人可以解釋,我想知道爲什麼id沒有被綁定到模板中。看來,如果你從指令中設置ID,它會正常工作。 (jsfiddle

@丹我還必須更改您的ID以使用前面的單詞test-,因爲HTML規範不允許ID以數字值開頭。根據規格:

ID和名稱標記必須以字母([A-Za-z])開頭,後面可以跟隨任意數量的字母,數字([0-9]),連字符( 「 - 」),下劃線(「_」),冒號(「:」)和句點(「。」)。

var testApp = angular.module('testApp',[]); 

testApp.controller('mainCtrl', ['$scope', function($scope) { 
    $scope.bar = [ 
     { id: 1, msg: 'this is a nice message'}, 
     { id: 2, msg: 'this message is also nice'}, 
     { id: 3, msg: 'yet another message'} 
    ]; 
}]); 

testApp.directive('plugin', function() { 
    return { 
     restrict : 'EA', 
     template: '<div>{{foo.msg}}</div>', 
     scope: {'foo': '='}, 
     compile: function compile(tElement, tAttrs, transclude) { 
      return { 
       post: function postLink(scope, element, iAttrs, controller) { 
        element.attr('id', 'test-' + scope.foo.id); 
        console.log(document.getElementById('test-' + scope.foo.id)); 
        /* This does not provide a null value */ 
       } 
      } 
     } 
    }; 
}); 
+1

Foo在控制器上定義,我用'scope:{foo ='='}'在指令的作用域上定義它。我只是試圖訪問它,所以我可以對元素進行一些DOM操作。 – Dan

+0

難道你只是使用元素變量修改DOM?任何機會,你可以得到一個jsfiddle說明你想要什麼? – Pete

+0

請參閱我上面提出的評論。我需要id字符串,並且該元素需要在那個時候編譯。 – Dan