【发布时间】:2016-02-25 01:51:15
【问题描述】:
我有以下控制器设置,以便我可以将检查的值添加到数组中,如下所示。
(function (app) {
'use strict';
app.controller('SimpleArrayCtrl', ['$scope', function SimpleArrayCtrl($scope) {
// fruits
$scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];
// selected fruits
$scope.selection = ['apple', 'pear'];
// toggle selection for a given fruit by name
$scope.toggleSelection = function toggleSelection(fruitName) {
var idx = $scope.selection.indexOf(fruitName);
// is currently selected
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
// is newly selected
else {
$scope.selection.push(fruitName);
}
};
}]);
})(angular.module('app', []));
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="SimpleArrayCtrl">
<div class="row">
<div class="col-md-6">
<h4>selectables</h4>
<form class="form-group" novalidate name="test">
<label ng-repeat="fruitName in fruits" class="checkbox-inline">
<input type="checkbox" name="selectedFruits[]" value="{{fruitName}}" ng-checked="selection.indexOf(fruitName) > -1" ng-click="toggleSelection(fruitName)"> {{fruitName}}
</label>
</form>
</div>
</div>
<div class="row">
<div class="col-md-6">
<h4>selection</h4>
<pre>{{selection|json}}</pre>
</div>
<div class="col-md-6">
<h4>inputs</h4>
<pre>{{fruits|json}}</pre>
</div>
<div class="col-md-6">
<h4>form</h4>
<pre>{{test|json}}</pre>
</div>
</div>
</div>
</div>
我要做的是将数组的值绑定到表单中,以便我可以提交数组的内容。
我已将ng-model 添加到我的复选框输入中,但我似乎只能将真假返回到我的数组而不是我的值
<input ng-model="fruitName" type="checkbox" name="selectedFruits[]" value="{{fruitName}}" ng-checked="selection.indexOf(fruitName) > -1" ng-click="toggleSelection(fruitName)">
如何将 selection 的值绑定到模型,并确保在单击时仍然可以使用刻度,以便在提交表单时提交数组的值?
【问题讨论】:
标签: javascript arrays angularjs angularjs-scope angular-ngmodel