2

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?

Crossfire
  • 1,801
  • 3
  • 21
  • 37

1 Answers1

3

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>
Community
  • 1
  • 1
dfsq
  • 191,768
  • 25
  • 236
  • 258