How to get the values and put them in array angularjs
16,706
You need to store the values in an object and then push it to array.
$scope.item = {};
$scope.addItem = function() {
var newItem = {};
newItem.name = $scope.item.name;
newItem.title = $scope.item.title;
$scope.contact.items.push(newItem);
console.log($scope.contact.items);
};
Related videos on Youtube
Author by
Sam Lewis
Updated on June 04, 2022Comments
-
Sam Lewis over 1 year
Here is my html: I have an object with arrays of items. I need to add a new array with values from inputs.
<div ng-repeat="item in contact.items"> <label for="Title">Title</label> <select id="Title" ng-model="item.title"> <option ng-selected="title.value === item.title" ng-repeat="title in titles"> {{ title.title }} </option> </select> </div> <div class="row"> <label for="Name"> Name</label> <input type="text" id="Name" placeholder="Name" ng-model="item.name"> </div> <div class="row"> <a ng-click="addItem();">Save Item</a> </div>
Here is the controller:
$scope.addItem = function() { $scope.contact.items.push({ name: "", title:"" }); console.log( $scope.contact.items); };
It is ok when I push the empty array, but it fails when I try pushing the values form the ng-model:
$scope.addItem = function() { $scope.contact.items.push({ name: $scope.item.name, title:$scope.item.title }); console.log( $scope.contact.items); };
What am I missing?
-
raina77ow over 8 yearsHow should a user specify a title for a new item?
-
Anil Singh over 8 yearsCan you setup the code on plnker?
-
-
Sam Lewis over 8 yearsI'm getting an error "Cannot read property 'name' of undefined' :(
-
M.S. over 8 yearsYou have to define item in $scope. Please see my updated answer.