Reputation: 381
I am very new to AngularJS and javascript in general. I was trying to create a very small app that lets add a User name and an Age, then shows the list of current users added, and their ages, here is some code I've wrote:
var main = angular.module("main",[]);
main.controller("AccountController",function(){
this.name = "";
this.age = ""
this.userList = [];
this.addUser = function (){
this.userList.push({name : this.name,age : this.age});
};
});
<body ng-app = "main" ng-controller = "AccountController as p" >
<input type = "text" placeholder = "name" ng-model = "p.name" />
<input type ="number" value = 25 ng-model = "p.age"/>
<button ng-click = "p.addUser()"> add </button>
<ul>
<li ng-repeat = "person in p.userList">{{person.name + ", " + person.age +" old ."}}</li>
</ul>
</body>
This code works perfectly, but this one doesn't:
var main = angular.module("main",[]);
main.controller("AccountController",function(){
this.user = {name : "",age : 0}
this.userList = [];
this.addUser = function (){
this.userList.push(this.user);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app = "main" ng-controller = "AccountController as p">
<input type = "text" placeholder = "name" ng-model = "p.user.name" />
<input type ="number" value = 16 ng-model = "p.user.age"/>
<button ng-click = "p.addUser()"> add </button>
<ul>
<li ng-repeat = "person in p.userList">{{person.name + ", " + person.age +" old ."}}</li>
</ul>
</body>
As you can see and test it, this code doesn't work like the 1st one, it changes automatically object's properties, but the first one doesn't change, it creates a new object and doesn't bind change object to the last object.
My problem is that I can't understand why they don't work the same way, since it's basically coded in the same way. I mean what's the difference between the two codes?
Upvotes: 3
Views: 71
Reputation: 1
Try
this.userList.push({name : this.user.name,age : this.user.age});
I think that in the second case, you push the object itself, and not only the values contained into the object.
Upvotes: 0
Reputation: 1816
In the first example you are creating new object. In the second example you are adding a reference to the object.
To make both examples behave in the same way you can write:
this.userList.push(angular.copy(this.user));
angular.copy
creates a deep copy of an object.
Upvotes: 2