angularjs - ngRepeat with ngInit - ngRepeat不刷新渲染值

Ada*_*ski 22 angularjs

我有使用ngRepeater显示的数组,但是使用此指令我正在使用ngInit指令,该指令执行应返回要显示的对象的函数.一切都很完美,但当我添加"新"按钮,我向数组添加新值,然后函数"SetPreview"只执行一次我认为应该执行函数取决于数组值的数量.我怎样才能做到这一点?

用户界面:

<body ng-app>

  <ul ng-controller="PhoneListCtrl">
      <button ng-click="add()">Add</button>
    <li ng-repeat="phone in phones" ng-init="displayedQuestion=SetPreview(phone);">
      {{displayedQuestion.name}}
      <p>{{displayedQuestion.snippet}}</p>
    </li>
  </ul>
</body>
Run Code Online (Sandbox Code Playgroud)

控制器:

function PhoneListCtrl($scope) {
  $scope.phones = [
    {"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™",
     "snippet": "The Next, Next Generation tablet."}
  ];

    $scope.add = function(){
        this.phones.push({name:'1', snippet:'n'});
    };        
    $scope.SetPreview = function(phone)
    {
        //here logic which can take object from diffrent location
        console.log(phone);
        return phone;
    };
}
Run Code Online (Sandbox Code Playgroud)

样本在这里 - jsfiddle

编辑:
这是更复杂的示例: - >现在电话集合为空,当您单击添加按钮时,新项目被添加并设置为可编辑(您可以更改文本字段中的值)并且当执行ngRender时SetPreview函数返回可编辑对象(它像预览一样工作).现在尝试再次单击"添加"按钮,您可以看到第一个项目的可编辑值仍然显示给用户,但我想刷新整个ng-repeater.

che*_*tts 16

您正在遇到Angular性能功能.

基本上Angular可以看到数组中的元素(例如'A')是相同的对象引用,因此它不会再次调用ng-init.这很有效.即使你将一个旧列表连接到一个新列表,Angular也会看到它是同一个引用.

相反,如果您创建一个与旧对象具有相同值的新对象,则它具有不同的引用,并且Angular重新编写它:执行您要查找的内容的错误示例:http://jsfiddle.net/fqnKt/37/

$scope.add = function(item) {
    var newItems = [];
    angular.forEach($scope.items, function(obj){
        this.push({val:obj.val});
    },newItems)

    newItems.push({val:item})
    $scope.items = newItems;
};
Run Code Online (Sandbox Code Playgroud)

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


Und*_*ied 8

我发现你可以ng-init{{}}隐藏块中的角度表达式替换:

<body ng-app>

<ul ng-controller="PhoneListCtrl">
    <button ng-click="add()">Add</button>
    <li ng-repeat="phone in phones">
      <span style="display: none">{{displayedQuestion=SetPreview(phone)}}</span>
      {{displayedQuestion.name}}
      <p>{{displayedQuestion.snippet}}</p>
    </li>
  </ul>
</body>
Run Code Online (Sandbox Code Playgroud)