0

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?

2
  • something like this? plnkr.co/edit/Mmxhdl9mQeg6fEdc6Bft?p=preview Commented Nov 30, 2013 at 0:26
  • @charlietfl Nope, I want to literally add input elements on clicking the button. Commented Nov 30, 2013 at 0:27

1 Answer 1

3

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

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.