angularjs - ngRepeat with ngInit - ngRepeat doesn't refresh rendered value

后端 未结 3 2011
误落风尘
误落风尘 2020-12-11 14:50

I have array which is displayed using ngRepeater but with this directive I\'m using ngInit directive which execute function which should return object to be displayed. Every

相关标签:
3条回答
  • 2020-12-11 15:03

    I've found out that you can just replace ng-init with angular expression {{}} in a hidden block:

    <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>
    
    0 讨论(0)
  • 2020-12-11 15:20

    If you have an ngInit in an element, and an ngRepeat in a descendant, the ngInit will only run once.

    To fix that, add an ngRepeat to the element with the ngInit, with an expression that repeats once and depends upon the same array (and other dependencies).

    For example:

    ng-repeat="_ in [ products ]" ng-init="total = 0"
    
    0 讨论(0)
  • 2020-12-11 15:29

    You are running into an Angular performance feature.

    Essentially Angular can see that the element in the array ('A' for example) is the same object reference, so it doesn't call ng-init again. This is efficient. Even if you concatenated an old list into a new list, Angular would see that it it the same reference.

    If instead you create a new object with the same values as the old object, it has a different reference and Angular re-inits it: Bad example that does what you are looking for: 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;
    };
    

    I don't recommend the approach taken in the fiddle, but rather you should find a different method than ng-init to trigger your code.

    0 讨论(0)
提交回复
热议问题