Alternative to using ng-init in 'view'?

I am trying to create an "how" function for my application. I want to be able to set the value of a dynamically generated number as a "similar number". The problem is using "ng-init" as the documentation says that this is a bad way to do it!

How do you set the value in the "controller" and not in the "view"?

Here is what I still have:

<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <script>document.write('<base href="' + document.location + '" />');</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>

Thank,

In JP

+5
source share
2 answers

Just change

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

per

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

If you still need a counter in the controller for some other reason (which I don’t see), create a controller, let's say FeedCtrland add it to your article:

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

And your FeedCtrl will be:

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

:

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

feeds , ng-bind .

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

{{likeCount}}
0

All Articles