2015-09-05 52 views
2

我想動態生成一個輸入列表,並使用AngularJS + jQuery將它們的值綁定到模型的數組屬性。AngularJS動態輸入值綁定到數組模型

... 
<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 + ']"> 
    ); 
}; 

爲什麼不能正常工作?

+0

我認爲你正在呼籲與click事件錯誤的函數。 –

+0

更新,謝謝。 – Crossfire

回答

3

首先,除非您完全理解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>