更新属性指令值

Update attribute directive value

本文关键字:指令 属性 更新      更新时间:2023-09-26

我是angular js的新手,我已经尝试了一些示例代码。我正在尝试一些东西,但它不起作用。下面的示例代码将详细说明这一点。

<body  ng-app="myApp" ng-controller="testController">
        <div repeat-hello-world="{{repeat}}">
            <button ng-repeat="i in [1,2,3]">{{i}}</button>
        </div>
</body>
Angular 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);           
        });
    };
});

你可以看到一行"This is not working"。当我试图改变值data-alert(这是属性指令),但它总是显示0。我也试着观察值的变化,但它不起作用。

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

问题在于,您依赖于在ng-repeat呈现后(即在$digest阶段之后)在之后添加警报属性。到那时,已经太晚了——您已经错过了修改DOM以使它们得到正确编译和链接的机会。

解决这个问题的方法是将ng-repeat放到父元素中,并声明性地添加'alert'属性:

    <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