1

I'm new to AngularJS, and this has been driving me nuts for several days. HELP!!! I've condensed the problem into as simple a code snippet as I could.. I've set up an array called indexArray in the Controller, and I want to push values to it from HTML via the function pushIndex(). The problem is that the push function adds ten identical elements to the array. When I list the array with the {{indexArray}} statement after the push, it looks like this:

[4,5,6,7,9,9,9,9,9,9,9,9,9,9]

Where I only wanted one "9" pushed, it added ten of them.

The same thing happens with strings, quotes, etc.

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script> 
var app = angular.module('myDataApp',[]);
app.controller('myDataController',function($scope, $http){
    $scope.indexArray=[4,5,6,7];
    $scope.pushIndex=function(num){
        $scope.indexArray.push(num);
   };
});
</script>
</head>
<body>
<div ng-app="myDataApp" ng-controller="myDataController">
{{ pushIndex(9) }}
{{ indexArray }}
</div>
</body>
</html>

Sorry in advance if the solution is painfully simple or this question has been asked before. Thanks! -UDM

1
  • This kind of angular expressions are ment to be side-effect free and angular will call your {{ pushIndex(9) }} expression many, many times (it won't even stop at 10). See this question for example. Commented Jul 28, 2016 at 22:17

1 Answer 1

3

Calling a function like this {{ pushIndex(9) }} will run the digest loop infinitely.

This will work for you instead

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script> 
var app = angular.module('myDataApp',[]);
app.controller('myDataController',function($scope, $http){
    $scope.indexArray=[4,5,6,7];
    $scope.pushIndex=function(num){
        $scope.indexArray.push(num);
   };
});
</script>
</head>
<body>
<div ng-app="myDataApp" ng-controller="myDataController">
<span ng-init="result=pushIndex(9)">{{result}}</span>
{{ indexArray }}
</div>
</body>
</html>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! This works like a charm, and ended five days of SHEER FRUSTRATION :-)
If you can please up vote and select this as the answer to this question, it would be much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.