JVG
JVG

Reputation: 21150

AngularJS adding inputs that represent an array model

Simple AngularJS questions that I can't get my head around.

Plunkr: http://plnkr.co/edit/OjaooVOQBEETkhaZFbWG?p=preview

HTML;

    <div ng-repeat="label in likedLabels">
         <input ng-model="likedLabels[$index]">
    </div>
    {{likedLabels}}
    <button ng-click="addInput()">+add more inputs</button>

JS:

   $scope.likedLabels = ['']
   $scope.addInput = function(){
     $scope.likedLabels.push('');
   }

I'm basically trying to create a user-operated way of adding input boxes and having the content inside linked to a model. What am I doing wrong here?

Upvotes: 0

Views: 3134

Answers (1)

charlietfl
charlietfl

Reputation: 171669

Use objects rather than primitives in your arrays. Directives like ng-repeat create separate child scopes for each repeated item in array.

Due to protoypical inheritance, objects will be passed as reference of original object to the child scope whereas primitives ( strings, booleans etc) won't. Thus there is no data binding of primitives in the scope tree

HTML

<div ng-repeat="item in likedLabels">
    <input ng-model="item.label">
</div>

JS

 $scope.likedLabels = []
  $scope.addInput = function() {
    $scope.likedLabels.push({label: ''});
  }

DEMO

Upvotes: 3

Related Questions