更新属性指令值
Update attribute directive value
我是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
相关文章:
- 具有{{}}指令属性的Angular
- AngularJs,在没有隔离的情况下将指令属性添加到作用域
- 如何使用指令属性值创建动态模板
- 通过指令属性传达操作
- AngularJS观察指令属性表达式,动态继承作用域
- 监视自定义指令属性在父作用域更改时不发生更改
- AngularJS:将$scope变量作为指令属性传递
- 指令 : 属性必须指定一个函数
- 将指令属性添加到指令元素
- 检查是否传递了指令属性
- 在 AngularJS 中计算指令属性中的表达式
- 将对象传递给 Angular 指令属性未通过
- AngularJS:无法从自定义指令属性中检索值以在自定义指令中解析
- 角度JS观察指令属性
- AngularJS指令属性在观察时不呈现值
- AngularJS:更改指令属性
- 正在访问控制器中的指令属性
- 在AngularJS中,当指令属性的作用域变量基于camelBase时,为什么它们需要用连字符分隔
- AngularJS将javascript对象绑定到指令属性
- 如何设置指令属性的默认值