使用ngInit – ngRepeat的angularjs – ngRepeat不会刷新渲染值

前端之家收集整理的这篇文章主要介绍了使用ngInit – ngRepeat的angularjs – ngRepeat不会刷新渲染值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有使用ngRepeater显示的数组,但是使用这个指令,我使用ngInit指令执行函数,该函数应该返回要显示的对象。一切正常工作,但是当我添加“新”按钮时,我将新值添加到数组,然后功能“SetPreview”只有在我认为应该根据数组值的数量执行功能时才执行。我怎样才能做到这一点?

用户界面:

  1. <body ng-app>
  2.  
  3. <ul ng-controller="PhoneListCtrl">
  4. <button ng-click="add()">Add</button>
  5. <li ng-repeat="phone in phones" ng-init="displayedQuestion=SetPreview(phone);">
  6. {{displayedQuestion.name}}
  7. <p>{{displayedQuestion.snippet}}</p>
  8. </li>
  9. </ul>
  10. </body>

控制器:

  1. function PhoneListCtrl($scope) {
  2. $scope.phones = [
  3. {"name": "Nexus S","snippet": "Fast just got faster with Nexus S."},{"name": "Motorola XOOM™ with Wi-Fi","snippet": "The Next,Next Generation tablet."},{"name": "MOTOROLA XOOM™",Next Generation tablet."}
  4. ];
  5.  
  6. $scope.add = function(){
  7. this.phones.push({name:'1',snippet:'n'});
  8. };
  9. $scope.SetPreview = function(phone)
  10. {
  11. //here logic which can take object from diffrent location
  12. console.log(phone);
  13. return phone;
  14. };
  15. }

Sample is here – jsfiddle

编辑:
Here is more complicated sample: – >现在收集的手机是空的,当你点击添加按钮新项目被添加并被设置为可编辑(您可以更改文本字段中的值),当ngRender执行时SetPreview函数返回可编辑对象(它的工作像预览)。现在尝试再次单击添加按钮,您可以看到第一个项目的可编辑值仍然呈现给用户,但是我想刷新整个ng-repeater。

你正在进行一个角色表演功能

基本角度可以看到数组中的元素(例如’A’)是相同的对象引用,所以它不会再次调用ng-init。这是有效的。即使您将一个旧列表连接到一个新的列表中,Angular也会看到它是相同的引用。

如果相反,您创建一个与旧对象具有相同值的新对象,则它具有不同的引用,并且Angular重新引用它:
错误的例子,你所寻找的:http://jsfiddle.net/fqnKt/37/

  1. $scope.add = function(item) {
  2. var newItems = [];
  3. angular.forEach($scope.items,function(obj){
  4. this.push({val:obj.val});
  5. },newItems)
  6.  
  7. newItems.push({val:item})
  8. $scope.items = newItems;
  9. };

我不推荐在小提琴中采用这种方法,而是应该找到一种不同的方法,ng-init来触发你的代码

猜你在找的Angularjs相关文章