Alternative to using ng-init in 'view'?

后端 未结 2 1560
闹比i
闹比i 2021-02-09 13:14

I am trying to create a \'like\' function for my app. I want to be able to set the value of a dynamically generated number as the \'like count\'. The problem comes in using \'ng

相关标签:
2条回答
  • 2021-02-09 13:27

    If your feeds object/array is long, it's better to use ng-bind for performance reasons.

    <span ng-bind="likeCount"></span>
    

    rather than

    {{likeCount}}
    
    0 讨论(0)
  • 2021-02-09 13:48

    Just change

    `<span ng-init="likeCount=feed.likes.length">{{likeCount}}</span>`
    

    per

    `<span>{{feed.likes.length}}</span>`.
    

    If you still need the count in the controller for some other reason (which I can't see), create a controller, let's assume FeedCtrl, and add it to your article:

    <article ng-repeat="feed in feeds" ng-controller="FeedCtrl">
      ...
      <span>{{likeCount}}</span>
    </article>
    

    And your FeedCtrl would be:

    function FeedCtrl($scope) {
      $scope.$watch('feed.likes.length', function(newValue) {
        $scope.likeCount = newValue;
      });
    }
    

    Yet another approach would be create a function to resolve you the value:

    <article ng-repeat="feed in feeds" ng-controller="FeedCtrl">
      ...
      <span>{{likeCount()}}</span>
    </article>
    
    function FeedCtrl($scope) {
      $scope.likeCount = function() {
        return $feed && $feed.likes ? $feed.likes.length : undefined;
      };
    }
    
    0 讨论(0)
提交回复
热议问题