我正在尝试动态生成输入列表,并使用 AngularJS + jQuery 将它们的值绑定(bind)到模型的数组属性。
...
<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>
关于javascript - AngularJS 动态输入值绑定(bind)到数组模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32412574/