Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
 
something like this? plnkr.co/edit/Mmxhdl9mQeg6fEdc6Bft?p=preview –  charlietfl 22 hours ago
 
@charlietfl Nope, I want to literally add input elements on clicking the button. –  Jascination 22 hours ago
add comment

1 Answer

up vote 2 down vote accepted

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.