I am trying to dynamically generate a list of inputs and bind their values to a model's array property using AngularJS + jQuery.

...
<section ng-controller="MyController">
  <button ng-click="addInput">Add new field</button>
  <section class="input-group"></section>
</section>

...
$scope.model = {
    'title': 'aaa',
    'arr': []
};

$scope.instructionCount = 0;

$scope.addInput = function() {
    $model.arr.push('');
    $('.input-group').append(
        '<input type="text"
         ng-bind="$scope.model.arr[' + ++$scope.instructionCount + ']">
    );
};

Why doesn't this work?

share|improve this question
    
I think you are calling wrong function with click event. – Salman Farsi Sep 5 '15 at 11:39
    
Updated, thank you. – Crossfire Sep 5 '15 at 11:50
up vote 2 down vote accepted

First of all until you fully understand the role of jQuery in frontend application I recommend you to remove it from your project and work with just Angular in Angular way.

Then you should use ngRepeat something like this:

var app = angular.module('demo', []);
app.controller('MainController', function($scope) {
    $scope.model = {
        'title': 'aaa',
        'arr': []
    };

    $scope.addField = function() {
        $scope.model.arr.push('');
    };
});
<script src="https://code.angularjs.org/1.4.3/angular.js"></script>
<div ng-app="demo" ng-controller="MainController">
    <section>
        <button ng-click="addField()">Add new field</button>
        <section class="input-group">
            <input type="text" ng-repeat="input in model.arr track by $index" ng-model="model.arr[$index]">
        </section>
        <pre>{{model | json}}</pre>
    </section>
</div>

share|improve this answer

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.