2

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?

2
  • 1
    How should a user specify a title for a new item? Commented Mar 26, 2015 at 9:54
  • 2
    Can you setup the code on plnker? Commented Mar 26, 2015 at 10:19

1 Answer 1

3

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);
};
Sign up to request clarification or add additional context in comments.

2 Comments

I'm getting an error "Cannot read property 'name' of undefined' :(
You have to define item in $scope. Please see my updated answer.

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.