JohnRobertPett JohnRobertPett - 3 months ago 11x
AngularJS Question

Alternative to using ng-init in 'view'?

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" >
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<script src=""></script>
<script src="app.js"></script>
<body ng-controller="MainCtrl">
<article ng-repeat="feed in feeds">
<button ng-click="likeClicked($index)">{{isLiked[$index]|liked}}</button>
<span ng-init="likeCount=feed.likes.length">{{likeCount}}</span>




Just change

`<span ng-init="likeCount=feed.likes.length">{{likeCount}}</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">

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">
function FeedCtrl($scope) {
  $scope.likeCount = function() {
    return $feed && $feed.likes ? $feed.likes.length : undefined;