2014-06-21 30 views
0

我是新的角js和我已經嘗試了幾個示例代碼。我正在嘗試一些東西,但它不起作用。下面的示例代碼將爲您提供更多的細節。更新屬性指令值

HTML代碼

<body ng-app="myApp" ng-controller="testController"> 
     <div repeat-hello-world="{{repeat}}"> 
      <button ng-repeat="i in [1,2,3]">{{i}}</button> 
     </div> 
</body> 

角JS代碼

'use strict'; 

angular.module('myApp.directives', []) 
    .directive('repeatHelloWorld', ['$timeout', function (timer) { 
    return { 
     compile: function(element, attributes) {    
      var hello = function(){     
       var nodes = element.children(); 
       console.log(nodes.length); 
       for(var i=0; i<nodes.length; ++i){     
        console.log(i);  
        angular.element(nodes[i]).attr('data-alert',i); // This is not working 
       }   
      } 

      element.ready(function(){ 
        hello(); 
      }); 

      var nodes = element.children(); 
       for(var i=0; i<nodes.length; ++i){ 
        console.log(nodes.length); 
        console.log(i); 
        angular.element(nodes[i]).attr('data-alert',i); 
       }   
     } 
    } 
}]); 
// Declare app level module which depends on filters, and services 
var myApp = angular.module('myApp', ['myApp.directives']); 

/* Controllers */ 
function testController($scope) { 
    $scope.repeat = 5; 
} 

myApp.directive("alert", function(){  
    return function(scope, element, attrs){ 

     attrs.$observe(attrs.alert , function(newValue){ 
      console.log('newval' + newValue); 
     }); 
     element.bind("click", function(){ 
      console.log(attrs.alert);   
     }); 
    }; 
}); 

你可以看到一行說: 「這是行不通的。」當我嘗試更改值數據警報(這是屬性指令),但它始終顯示0.我也嘗試觀察值的變化,但它不工作。

小提琴:http://jsfiddle.net/U7N9n/2/

+0

你可以發佈一個小提琴? – pixelbits

+0

我添加了小提琴鏈接並更新了我的問題。 – dotnetstep

回答

0

的問題是,你在添加警報依託屬性後的NG-重複已呈現(在$之後意味着消化階段)。屆時,爲時已晚 - 您錯過了修改DOM的機會,以便它們能夠正確編譯和鏈接。

解決這個問題的辦法是把你的NG-重複的父元素,並添加聲明「警報」屬性:

<div repeat-hello-world="{{repeat}}"> 
     <span ng-repeat="i in [1,2,3]"> 
     <button data-alert="{{i}}">{{i}}</button> 
     </span> 
    </div> 

Here is a Working Fiddle

+0

是的,你是對的,但如果我們必須在渲染DOM後進行更新。這是我正在尋找的。 – dotnetstep