Alternative to using ng-init in 'view'?

All we need is an easy explanation of the problem, so here it is.

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-init’, as the documentation says this is a bad way to do it!

How do you set the value in the ‘controller’ rather than the ‘view’?

Here is what I have so far:

<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <script>document.write('<base href="' + document.location + '" rel="nofollow noreferrer noopener" />');</script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
  <article ng-repeat="feed in feeds">
    <h3>{{feed.createdby}}</h3>
    <p>{{feed.content}}</p>
    <button ng-click="likeClicked($index)">{{isLiked[$index]|liked}}</button>
    <span ng-init="likeCount=feed.likes.length">{{likeCount}}</span>
  </article>
</body>
</html>

Thanks,

JP

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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;
  };
}

Method 2

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}}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply