为什么我的角度函数被调用超过数组的长度?

时间:2016-02-23 12:53:55

标签: arrays angularjs

我试图找出为什么我的角度应用程序陷入无限循环,而调查引导我这个简单的问题。我有一系列id和模型数组。我试图显示id列表中的所有模型。请参阅https://jsfiddle.net/SNummelin/hyow2fL6/中的控制台日志记录。

控制台日志:

(index):57 getModel called with 111
(index):57 getModel called with 111
(index):57 getModel called with 222
(index):57 getModel called with 222
(index):57 getModel called with 111
(index):57 getModel called with 222

HTML:

<div ng-controller="TestCtrl">
  {{modelIds.length}} / {{models.length}}
  <div ng-repeat="id in modelIds">
    <div ng-bind-html=getModel(id)></div>
  </div>
</div>

角:

angular.module('myApp', [])
  .controller('TestCtrl', function($scope, $sce) {
    $scope.modelIds = ['111', '222'];
    $scope.models = [{
      id: '111',
      name: "Eka"
    }, {
      id: '222',
      name: "Eka"
    }];

  $scope.getModel = function(id) {
    console.log("getModel called with " + id);
    var ret = "";
    $scope.models.forEach(function(model) {
      if (model.id === id)
        ret += model.name;
      }, this);
    return $sce.trustAsHtml("<div>" + ret + "</div>");
  }
});

0 个答案:

没有答案