Angular.js 坑坑 更健康

来源:互联网 发布:windows 8 airplay 编辑:程序博客网 时间:2024/05/02 23:20

ng-repeat


参考 http://segmentfault.com/q/1010000000405730

<div ng-init="words = [1,1,1]" ng-repeat="word in words"> {{word}}</div>

报错:ngRepeat:dupes

原因:数组中有2个以上的相同值。

修复: 加上 track by $index ,<div ng-init="words = [1,1,1]" ng-repeat="word in wordstrack by $index"> {{word}}</div>


ng-repeat 及 scope 原型继承

ng-repeat 会为内部 循环生成的每个 item 内的指令 applyScope的时候 会生成一个new sub-scope,而且在 这每个new scope调用scope.$apply() 之前 scope的应用还是指向 之前的

parent scope

<input  ng-model="color" value="blue"/>

<div ng-repeat="x in xx"><hello-world></hello-world></div>

app.directive('helloWorld',function(){
return {
         //scope: true, //使用一个继承父作用域的自作用域   
         restrict: 'AEC',
         replace: true,
         template: '<h3 style="background-color:{{color}}">Hello World!</h3>',
         link: function(scope,elem,attr){
         elem.bind('click',function(){
         scope.$apply(function(){  
         scope.color='red'      //注意这里
});  
})
elem.bind('mouseover',function(){
elem.css('cursor','pointer');
});
}
}
});


如果你改变 input的值 你会 发现 多个 hello-world 标签都 会随之 改变颜色。但是 一旦你点击其中一个hello-world 会发现只有你点击的那个 颜色变成红色。而且对应的input里的值也没受 双向绑定的 影响。这是因为在 指令helloWorld 内注册 事件的方法 link里当你apply的时候 对应的scope是一个new 子scope,只能影响自己。那我们应该怎么办呢?scope.color 替换成  scope.$parent.color 就可以了




0 0
原创粉丝点击