Reputation: 5076
I am new to AngularJs and Javascript, so I am going to do my best to try to explain the problem. My Angular controller receives data from a method in my MVC Controller. Each time the script is run, the MVC Controller returns 1 item. I am trying to dynamically expand the item list in my html page each time a new item is returned using ng-repeat in an unordered list. When I use ng-repeat, the first item does not show until the second item is added and then they both show together. If I add a 3rd item, the items display strangely. Here is an example of iterations with ng-repeat:
Iteration 1:
blank
Iteration 2:
Item 1
Item 2
Iteration 3:
["Item1", "Item2"]
Item 3
The 3rd iteration literally shows up with the brackets and the quotation marks instead of the bullets for the unordered list. Can anyone tell me what is happening?
Here is the Angular controller code:
$scope.addState = function () {
//debugger;
companyService.addState($scope.form)
.success(function (data) {
if (pass == 0) {
$scope.addedStates = data;
pass = pass + 1;
}
else {
addedStates = [
angular.copy($scope.addedStates),
data
];
$scope.addedStates = addedStates;
}
$scope.rmgStates = $scope.rmgStates - 1;
if($scope.rmgStates == 0)
{
$scope.canSubmit = true;
$scope.lastState = false;
}
else {
$scope.canSubmit = false;
$scope.lastState = true;
}
})
};
Here is the html code:
You have added the following States:<br />
<ul>
<li ng-repeat="item in addedStates">
{{item}}
</li>
</ul>
Any and all help is greatly appreciated.
Upvotes: 1
Views: 362
Reputation: 6467
The way to add new items in an array is the following. Use:
$scope.addedStates.push(data);
Instead of:
if (pass == 0) {
$scope.addedStates = data;
pass = pass + 1;
}
else {
addedStates = [
angular.copy($scope.addedStates),
data
];
$scope.addedStates = addedStates;
}
Upvotes: 1
Reputation: 6676
The problem is that on the first pass, you were setting addedStates to the single state that was added -- because ng-repeat expects and array, it wasn't displaying anything. On passes after the first, you were taking the previous addedstates, wrapping it with an array and then inserting into an array along with the new state thus going a level deeper each time -- which is why the second time it was showing the correct format, but the third, it was an array within an array.
Instead, you should initialize and empty array and on each successful request to add a state, just push the new state into the existing array.
Try this:
$scope.addedStates = [];
$scope.addState = function () {
//debugger;
companyService.addState($scope.form)
.success(function (data) {
$scope.addedStates.push(angular.copy(data));
$scope.rmgStates = $scope.rmgStates - 1;
if($scope.rmgStates == 0)
{
$scope.canSubmit = true;
$scope.lastState = false;
}
else {
$scope.canSubmit = false;
$scope.lastState = true;
}
})
};
Upvotes: 2