Reputation: 513
I'm having a weird issue (I'm very new to angular and even JS, however I believe this should work as I tested it using node in my terminal and it was fine). I've created a button that basically should add "hi" as an entry to an array. However, it only adds it once, and then stop working. I expected it to just continue to add "hi", "hi"...etc. – I should mention this was using "push".
So I've tried the following, getting the index of the last entry, and then adding "hi" as the new entry as seen below:
$scope.attend2 = function() {
arrayLength = $scope.eventAttending.length;
$scope.eventAttending[arrayLength] = "Hi";
};
I'm still having the same issue. I first fed in the index of the last array entry as the data, and this would work fine because the data being added was different each time (e.g. eventAttending[1] = 1 then eventAttending[2] = 2), However it seems to not work when it's the same data;e.g. eventAttending[1] = "hi" then eventAttending[2] = "hi" – in this case I get "hi" in array index 1, but it stops there.
Thanks for any help,
Chris
Upvotes: 1
Views: 77
Reputation: 1730
The problem is that you are using that array inside an ng-repeat, and by default, that directive uses content to differentiate items.
You can solve it using 'track by' to change the variable it uses to track elements:
<div ng-repeat="item in items track by $index">{{item}}</div>
Upvotes: 0
Reputation: 680
You could maybe try to make the array multi dimensional:
$scope.eventAttending=[];
$scope.attend2 = function() {
var arrayLength = $scope.eventAttending.length;
$scope.eventAttending.push({arrayLength:"Hi"});
};
Upvotes: 0
Reputation: 13238
Just define an empty array in the controller and push the string message on click event of button
Example
angular.module('app', [])
.controller('myCtrl', function($scope) {
$scope.hiArray = [];
$scope.onClick=function(){
$scope.hiArray.push('Hi');
}
})
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@*" data-semver="1.2.10" src="http://code.angularjs.org/1.2.10/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="app" ng-controller="myCtrl">
<button ng-click="onClick()" >Add Hi</button> <br>
{{hiArray}}
</body>
</html>
Upvotes: 1
Reputation: 680
Try pushing the value in the array:
$scope.eventAttending.push("Hi");
Upvotes: 1