AngularJS 动态输入值绑定到数组模型

AngularJS dynamic input value binding to an array model

我正在尝试使用 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 + ']">
    );
};

为什么这不起作用?

首先,在您完全理解 jQuery 在前端应用程序中的作用之前,我建议您将其从您的项目中删除,并在 Angular way 中仅使用 Angular。

那么你应该像这样使用 ngRepeat:

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>