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?

1
  • I think you are calling wrong function with click event. Commented Sep 5, 2015 at 11:39

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

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.