How do I bind to list of checkbox values with AngularJS?
我有几个复选框:
1 2 3 4 | <input type='checkbox' value="apple" checked> <input type='checkbox' value="orange"> <input type='checkbox' value="pear" checked> <input type='checkbox' value="naartjie"> |
我希望绑定到我的控制器中的一个列表,这样每当一个复选框被更改时,控制器就维护一个所有选中值的列表,例如,
ng模型似乎只能将单个复选框的值绑定到控制器中的变量。
有没有其他方法可以这样做,以便我可以将四个复选框绑定到控制器中的列表?
解决这个问题有两种方法。使用简单的数组或对象数组。每个解决方案都有其优缺点。在下面,您将为每个箱子找到一个。
以简单数组作为输入数据HTML可能看起来像:
1 2 3 4 5 6 7 8 9 | <label ng-repeat="fruitName in fruits"> <input type="checkbox" name="selectedFruits[]" value="{{fruitName}}" ng-checked="selection.indexOf(fruitName) > -1" ng-click="toggleSelection(fruitName)" > {{fruitName}} </label> |
适当的控制器代码是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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); } }; }]); |
优点:简单的数据结构和按名称切换易于处理
缺点:添加/删除很麻烦,因为必须管理两个列表(输入和选择)
以对象数组作为输入数据HTML可能看起来像:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <label ng-repeat="fruit in fruits"> <!-- - Use `value="{{fruit.name}}"` to give the input a real value, in case the form gets submitted traditionally - Use `ng-checked="fruit.selected"` to have the checkbox checked based on some angular expression (no two-way-data-binding) - Use `ng-model="fruit.selected"` to utilize two-way-data-binding. Note that `.selected` is arbitrary. The property name could be anything and will be created on the object if not present. --> <input type="checkbox" name="selectedFruits[]" value="{{fruit.name}}" ng-model="fruit.selected" > {{fruit.name}} </label> |
适当的控制器代码是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | app.controller('ObjectArrayCtrl', ['$scope', 'filterFilter', function ObjectArrayCtrl($scope, filterFilter) { // Fruits $scope.fruits = [ { name: 'apple', selected: true }, { name: 'orange', selected: false }, { name: 'pear', selected: true }, { name: 'naartjie', selected: false } ]; // Selected fruits $scope.selection = []; // Helper method to get selected fruits $scope.selectedFruits = function selectedFruits() { return filterFilter($scope.fruits, { selected: true }); }; // Watch fruits for changes $scope.$watch('fruits|filter:{selected:true}', function (nv) { $scope.selection = nv.map(function (fruit) { return fruit.name; }); }, true); }]); |
优点:添加/删除非常简单
缺点:数据结构比较复杂,按名称切换比较麻烦,或者需要一个助手方法
演示:http://jsbin.com/imaquc/1/
一个简单的解决方案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <label ng-repeat="(color,enabled) in colors"> <input type="checkbox" ng-model="colors[color]" /> {{color}} </label> <p> colors: {{colors}} </p> var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope){ $scope.colors = {Blue: true, Orange: true}; }); |
http://plnkr.co/edit/u4vd61?P=预览
1 2 | <input type='checkbox' ng-repeat="fruit in fruits" ng-checked="checkedFruits.indexOf(fruit) != -1" ng-click="toggleCheck(fruit)"> |
.
1 2 3 4 5 6 7 8 9 10 11 | function SomeCtrl ($scope) { $scope.fruits = ["apple, orange, pear, naartjie"]; $scope.checkedFruits = []; $scope.toggleCheck = function (fruit) { if ($scope.checkedFruits.indexOf(fruit) === -1) { $scope.checkedFruits.push(fruit); } else { $scope.checkedFruits.splice($scope.checkedFruits.indexOf(fruit), 1); } }; } |
这里有一个快速的、可重用的指令,它似乎可以完成您想要做的事情。我只是简单地称它为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | app.directive('checkList', function() { return { scope: { list: '=checkList', value: '@' }, link: function(scope, elem, attrs) { var handler = function(setup) { var checked = elem.prop('checked'); var index = scope.list.indexOf(scope.value); if (checked && index == -1) { if (setup) elem.prop('checked', false); else scope.list.push(scope.value); } else if (!checked && index != -1) { if (setup) elem.prop('checked', true); else scope.list.splice(index, 1); } }; var setupHandler = handler.bind(null, true); var changeHandler = handler.bind(null, false); elem.bind('change', function() { scope.$apply(changeHandler); }); scope.$watch('list', setupHandler, true); } }; }); |
这里有一个控制器和一个视图,显示了如何使用它。
1 2 3 4 5 6 7 8 | <span ng-repeat="fruit in fruits"> <input type='checkbox' value="{{fruit}}" check-list='checked_fruits'> {{fruit}}<br /> </span> The following fruits are checked: {{checked_fruits | json}} Add fruit to the array manually: <button ng-repeat="fruit in fruits" ng-click='addFruit(fruit)'>{{fruit}}</button> |
1 2 3 4 5 6 7 8 | app.controller('MainController', function($scope) { $scope.fruits = ['apple', 'orange', 'pear', 'naartjie']; $scope.checked_fruits = ['apple', 'pear']; $scope.addFruit = function(fruit) { if ($scope.checked_fruits.indexOf(fruit) != -1) return; $scope.checked_fruits.push(fruit); }; }); |
(按钮显示更改数组也将更新复选框。)
最后,下面是一个关于Punker的指令示例:http://plnkr.co/edit/3ynlsyog4pibw6kj7drk?P=预览
基于此线程中的答案,我创建了涵盖所有情况的清单模型指令:
- 简单的基元数组
- 对象数组(拾取ID或整个对象)
- 对象属性迭代
对于主题启动案例,它将是:
1 2 3 | <label ng-repeat="fruit in ['apple', 'orange', 'pear', 'naartjie']"> <input type="checkbox" checklist-model="selectedFruits" checklist-value="fruit"> {{fruit}} </label> |
VitaliyPotapov对Github的
我花了几个小时试图让其他解决方案在没有运气的情况下工作。干得好,维塔莱特!!
使用EDOCX1[5]字符串有助于使用选定值的哈希图:
1 2 3 4 5 6 7 8 9 | <ul> <li ng-repeat="someItem in someArray"> <input type="checkbox" ng-model="someObject[$index.toString()]" /> </li> </ul> |
这样就可以用表示索引的键更新ng模型对象。
1 | $scope.someObject = {}; |
过了一会儿,
1 2 3 4 5 | $scope.someObject = { 0: true, 4: false, 1: true }; |
这种方法不适用于所有情况,但很容易实现。
既然你接受了一个没有使用列表的答案,我假设我的评论问题的答案是"不,它不必是列表"。我也有这样的印象,也许你是在渲染HTML服务器端,因为在你的示例HTML中存在"选中"的内容(如果使用ng模型来为你的复选框建模,则不需要这样做)。
不管怎样,当我问这个问题时,我想到的是,假设您正在生成HTML服务器端:
1 2 3 4 5 6 7 | <div ng-controller="MyCtrl" ng-init="checkboxes = {apple: true, orange: false, pear: true, naartjie: false}"> <input type="checkbox" ng-model="checkboxes.apple">apple <input type="checkbox" ng-model="checkboxes.orange">orange <input type="checkbox" ng-model="checkboxes.pear">pear <input type="checkbox" ng-model="checkboxes.naartjie">naartjie {{checkboxes}} |
ng init允许服务器端生成的HTML最初设置某些复选框。
小提琴。
我认为最简单的解决方法是使用指定了"multiple"的"select":
1 | <select ng-model="selectedfruit" multiple ng-options="v for v in fruit"></select> |
否则,我认为您必须处理列表才能构建列表(通过
以下解决方案似乎是一个不错的选择,
1 2 3 4 5 6 7 | <label ng-repeat="fruit in fruits"> <input type="checkbox" ng-model="fruit.checked" ng-value="true" > {{fruit.fruitName}} </label> |
在控制器模型中,
1 2 3 4 5 6 7 8 9 10 11 12 13 | $scope.fruits = [ { "name":"apple", "checked": true }, { "name":"orange" }, { "name":"grapes", "checked": true } ]; |
我已经调整了Yoshi接受的答案来处理复杂的对象(而不是字符串)。
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <p ng-repeat="permission in allPermissions"> <input type="checkbox" ng-checked="selectedPermissions.containsObjectWithProperty('id', permission.id)" ng-click="toggleSelection(permission)" /> {{permission.name}} </p> <hr /> <p> allPermissions: | <span ng-repeat="permission in allPermissions">{{permission.name}} | </span> </p> <p> selectedPermissions: | <span ng-repeat="permission in selectedPermissions">{{permission.name}} | </span> </p> |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | Array.prototype.indexOfObjectWithProperty = function(propertyName, propertyValue) { for (var i = 0, len = this.length; i < len; i++) { if (this[i][propertyName] === propertyValue) return i; } return -1; }; Array.prototype.containsObjectWithProperty = function(propertyName, propertyValue) { return this.indexOfObjectWithProperty(propertyName, propertyValue) != -1; }; function TestController($scope) { $scope.allPermissions = [ {"id" : 1,"name" :"ROLE_USER" }, {"id" : 2,"name" :"ROLE_ADMIN" }, {"id" : 3,"name" :"ROLE_READ" }, {"id" : 4,"name" :"ROLE_WRITE" } ]; $scope.selectedPermissions = [ {"id" : 1,"name" :"ROLE_USER" }, {"id" : 3,"name" :"ROLE_READ" } ]; $scope.toggleSelection = function toggleSelection(permission) { var index = $scope.selectedPermissions.indexOfObjectWithProperty('id', permission.id); if (index > -1) { $scope.selectedPermissions.splice(index, 1); } else { $scope.selectedPermissions.push(permission); } }; } |
工作示例:http://jsfiddle.net/tcu8v/
另一个简单的指令可能是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | var appModule = angular.module("appModule", []); appModule.directive("checkList", [function () { return { restrict:"A", scope: { selectedItemsArray:"=", value:"@" }, link: function (scope, elem) { scope.$watchCollection("selectedItemsArray", function (newValue) { if (_.contains(newValue, scope.value)) { elem.prop("checked", true); } else { elem.prop("checked", false); } }); if (_.contains(scope.selectedItemsArray, scope.value)) { elem.prop("checked", true); } elem.on("change", function () { if (elem.prop("checked")) { if (!_.contains(scope.selectedItemsArray, scope.value)) { scope.$apply( function () { scope.selectedItemsArray.push(scope.value); } ); } } else { if (_.contains(scope.selectedItemsArray, scope.value)) { var index = scope.selectedItemsArray.indexOf(scope.value); scope.$apply( function () { scope.selectedItemsArray.splice(index, 1); }); } } console.log(scope.selectedItemsArray); }); } }; }]); |
控制器:
1 2 3 4 5 6 7 8 9 10 11 12 13 | appModule.controller("sampleController", ["$scope", function ($scope) { //#region"Scope Members" $scope.sourceArray = [{ id: 1, text:"val1" }, { id: 2, text:"val2" }]; $scope.selectedItems = ["1"]; //#endregion $scope.selectAll = function () { $scope.selectedItems = ["1","2"]; }; $scope.unCheckAll = function () { $scope.selectedItems = []; }; }]); |
和HTML:
1 2 3 4 5 6 7 8 9 10 | <ul class="list-unstyled filter-list"> <li data-ng-repeat="item in sourceArray"> <label> <input type="checkbox" check-list selected-items-array="selectedItems" value="{{item.id}}"> {{item.text}} </label> </li> |
我还包括一个抢劫犯:http://plnkr.co/edit/xnftyij4ed6ryfwnfn6v?P=预览
签出这个有效管理复选框列表的指令。我希望它对你有用。清单模型
你不必写所有的代码。AngularJS只需使用ngRueValue和ngFalseValue就可以保持模型和复选框的同步。
这里是codepen:http://codepen.io/paulbhartzog/pen/kbhzn
代码片段:
1 2 3 4 5 | <p ng-repeat="item in list1" class="item" id="{{item.id}}"> {{item.id}} <input name='obj1_data' type="checkbox" ng-model="list1[$index].data" ng-true-value="1" ng-false-value="0"> Click this to change data value below </p> [cc lang="javascript"]{{list1 | json}} |
< /代码>
有一种方法可以直接在阵列上工作,同时通过
技巧是在NG模型中使用getter/setter函数。这样,您可以使用数组作为真实模型,并"假"输入模型中的布尔值:
1 2 3 4 5 6 7 | <label ng-repeat="fruitName in ['apple', 'orange', 'pear', 'naartjie']"> <input type="checkbox" ng-model="fruitsGetterSetterGenerator(fruitName)" ng-model-options="{ getterSetter: true }" > {{fruitName}} </label> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | $scope.fruits = ['apple', 'pear']; // pre checked $scope.fruitsGetterSetterGenerator = function(fruitName){ return function myGetterSetter(nowHasFruit){ if (nowHasFruit !== undefined){ // Setter fruitIndex = $scope.fruits.indexOf(fruit); didHaveFruit = (fruitIndex !== -1); mustAdd = (!didHaveFruit && nowHasFruit); mustDel = (didHaveFruit && !nowHasFruit); if (mustAdd){ $scope.fruits.push(fruit); } if (mustDel){ $scope.fruits.splice(fruitIndex, 1); } } else { // Getter return $scope.user.fruits.indexOf(fruit) !== -1; } } } |
注意,如果数组很大,那么不应该使用此方法,因为
有关更多信息,请参阅https://docs.angularjs.org/api/ng/directive/ngmodeloptions。
可以将AngularJS和JQuery组合在一起。例如,您需要在控制器中定义一个数组,
1 2 3 | <label ng-repeat="item in items"> <input type="checkbox" ng-model="selected[$index]" ng-true-value="'{{item}}'">{{item}} </label> |
您可以获取拥有所选项目的数组。使用方法
这里还有另一个解决方案。我的解决方案的好处:
- 它不需要任何额外的手表(可能会影响性能)
- 它不需要控制器中的任何代码来保持其干净
- 代码还是有点短
- 它只需要很少的代码就可以在多个地方重用,因为它只是一个指令
指令如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | function ensureArray(o) { var lAngular = angular; if (lAngular.isArray(o) || o === null || lAngular.isUndefined(o)) { return o; } return [o]; } function checkboxArraySetDirective() { return { restrict: 'A', require: 'ngModel', link: function(scope, element, attrs, ngModel) { var name = attrs.checkboxArraySet; ngModel.$formatters.push(function(value) { return (ensureArray(value) || []).indexOf(name) >= 0; }); ngModel.$parsers.push(function(value) { var modelValue = ensureArray(ngModel.$modelValue) || [], oldPos = modelValue.indexOf(name), wasSet = oldPos >= 0; if (value) { if (!wasSet) { modelValue = angular.copy(modelValue); modelValue.push(name); } } else if (wasSet) { modelValue = angular.copy(modelValue); modelValue.splice(oldPos, 1); } return modelValue; }); } } } |
最后,就这样使用它:
1 | <input ng-repeat="fruit in ['apple', 'banana', '...']" type="checkbox" ng-model="fruits" checkbox-array-set="{{fruit}}" /> |
这就是一切。唯一的添加是
我喜欢Yoshi的回答。我对它进行了增强,这样您就可以对多个列表使用相同的功能。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <label ng-repeat="fruitName in fruits"> <input type="checkbox" name="selectedFruits[]" value="{{fruitName}}" ng-checked="selection.indexOf(fruitName) > -1" ng-click="toggleSelection(fruitName, selection)"> {{fruitName}} </label> <label ng-repeat="veggieName in veggies"> <input type="checkbox" name="selectedVeggies[]" value="{{veggieName}}" ng-checked="veggieSelection.indexOf(veggieName) > -1" ng-click="toggleSelection(veggieName, veggieSelection)"> {{veggieName}} </label> app.controller('SimpleArrayCtrl', ['$scope', function SimpleArrayCtrl($scope) { // fruits $scope.fruits = ['apple', 'orange', 'pear', 'naartjie']; $scope.veggies = ['lettuce', 'cabbage', 'tomato'] // selected fruits $scope.selection = ['apple', 'pear']; $scope.veggieSelection = ['lettuce'] // toggle selection for a given fruit by name $scope.toggleSelection = function toggleSelection(selectionName, listSelection) { var idx = listSelection.indexOf(selectionName); // is currently selected if (idx > -1) { listSelection.splice(idx, 1); } // is newly selected else { listSelection.push(selectionName); } }; }]); |
http://plnkr.co/edit/kcbtzeynma8s1x7hja8p?P=预览
在HTML中(假设复选框位于表中每行的第一列)。
1 2 3 4 5 6 | <tr ng-repeat="item in fruits"> <td><input type="checkbox" ng-model="item.checked" ng-click="getChecked(item)"></td> <td ng-bind="fruit.name"></td> <td ng-bind="fruit.color"></td> ... </tr> |
在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | // The data initialization part... $scope.fruits = [ { name: ...., color:.... }, { name: ...., color:.... } ... ]; // The checked or not data is stored in the object array elements themselves $scope.fruits.forEach(function(item){ item.checked = false; }); // The array to store checked fruit items $scope.checkedItems = []; // Every click on any checkbox will trigger the filter to find checked items $scope.getChecked = function(item){ $scope.checkedItems = $filter("filter")($scope.fruits,{checked:true}); }; |
如果同一表单上有多个复选框
控制器代码
1 2 3 4 | vm.doYouHaveCheckBox = ['aaa', 'ccc', 'bbb']; vm.desiredRoutesCheckBox = ['ddd', 'ccc', 'Default']; vm.doYouHaveCBSelection = []; vm.desiredRoutesCBSelection = []; |
查看代码
1 2 3 4 5 6 7 8 9 10 11 | <input id="{{doYouHaveOption}}" type="checkbox" value="{{doYouHaveOption}}" ng-checked="vm.doYouHaveCBSelection.indexOf(doYouHaveOption) > -1" ng-click="vm.toggleSelection(doYouHaveOption,vm.doYouHaveCBSelection)" /> <label for="{{doYouHaveOption}}"></label> {{doYouHaveOption}} <input id="{{desiredRoutesOption}}" type="checkbox" value="{{desiredRoutesOption}}" ng-checked="vm.desiredRoutesCBSelection.indexOf(desiredRoutesOption) > -1" ng-click="vm.toggleSelection(desiredRoutesOption,vm.desiredRoutesCBSelection)" /> <label for="{{desiredRoutesOption}}"></label> {{desiredRoutesOption}} |
灵感来源于上面的Yoshi的帖子。这是PLNKR。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | (function () { angular .module("APP", []) .controller("demoCtrl", ["$scope", function ($scope) { var dc = this dc.list = [ "Selection1", "Selection2", "Selection3" ] dc.multipleSelections = [] dc.individualSelections = [] // Using splice and push methods to make use of // the same"selections" object passed by reference to the // addOrRemove function as using"selections = []" // creates a new object within the scope of the // function which doesn't help in two way binding. dc.addOrRemove = function (selectedItems, item, isMultiple) { var itemIndex = selectedItems.indexOf(item) var isPresent = (itemIndex > -1) if (isMultiple) { if (isPresent) { selectedItems.splice(itemIndex, 1) } else { selectedItems.push(item) } } else { if (isPresent) { selectedItems.splice(0, 1) } else { selectedItems.splice(0, 1, item) } } } }]) })() |
1 2 3 | label { display: block; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="style.css" /> </head> <body ng-app="APP" ng-controller="demoCtrl as dc"> checkbox-select demo <h4>Multiple Selections</h4> <label ng-repeat="thing in dc.list"> <input type="checkbox" ng-checked="dc.multipleSelections.indexOf(thing) > -1" ng-click="dc.addOrRemove(dc.multipleSelections, thing, true)" > {{thing}} </label> <p> dc.multipleSelections :- {{dc.multipleSelections}} </p> <h4>Individual Selections</h4> <label ng-repeat="thing in dc.list"> <input type="checkbox" ng-checked="dc.individualSelections.indexOf(thing) > -1" ng-click="dc.addOrRemove(dc.individualSelections, thing, false)" > {{thing}} </label> <p> dc.invidualSelections :- {{dc.individualSelections}} </p> <script data-require="[email protected]" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"> <script data-require="[email protected]" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.min.js"> <script src="script.js"> </body> </html> |
基于我在这里的其他文章,我做了一个可重用的指令。
查看Github存储库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | (function () { angular .module("checkbox-select", []) .directive("checkboxModel", ["$compile", function ($compile) { return { restrict:"A", link: function (scope, ele, attrs) { // Defining updateSelection function on the parent scope if (!scope.$parent.updateSelections) { // Using splice and push methods to make use of // the same"selections" object passed by reference to the // addOrRemove function as using"selections = []" // creates a new object within the scope of the // function which doesn't help in two way binding. scope.$parent.updateSelections = function (selectedItems, item, isMultiple) { var itemIndex = selectedItems.indexOf(item) var isPresent = (itemIndex > -1) if (isMultiple) { if (isPresent) { selectedItems.splice(itemIndex, 1) } else { selectedItems.push(item) } } else { if (isPresent) { selectedItems.splice(0, 1) } else { selectedItems.splice(0, 1, item) } } } } // Adding or removing attributes ele.attr("ng-checked", attrs.checkboxModel +".indexOf(" + attrs.checkboxValue +") > -1") var multiple = attrs.multiple ?"true" :"false" ele.attr("ng-click","updateSelections(" + [attrs.checkboxModel, attrs.checkboxValue, multiple].join(",") +")") // Removing the checkbox-model attribute, // it will avoid recompiling the element infinitly ele.removeAttr("checkbox-model") ele.removeAttr("checkbox-value") ele.removeAttr("multiple") $compile(ele)(scope) } } }]) // Defining app and controller angular .module("APP", ["checkbox-select"]) .controller("demoCtrl", ["$scope", function ($scope) { var dc = this dc.list = [ "selection1", "selection2", "selection3" ] // Define the selections containers here dc.multipleSelections = [] dc.individualSelections = [] }]) })() |
1 2 3 | label { display: block; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="style.css" /> </head> <body ng-app="APP" ng-controller="demoCtrl as dc"> checkbox-select demo <h4>Multiple Selections</h4> <label ng-repeat="thing in dc.list"> <input type="checkbox" checkbox-model="dc.multipleSelections" checkbox-value="thing" multiple> {{thing}} </label> <p> dc.multipleSelecitons:- {{dc.multipleSelections}} </p> <h4>Individual Selections</h4> <label ng-repeat="thing in dc.list"> <input type="checkbox" checkbox-model="dc.individualSelections" checkbox-value="thing"> {{thing}} </label> <p> dc.individualSelecitons:- {{dc.individualSelections}} </p> <script data-require="[email protected]" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"> <script data-require="[email protected]" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.min.js"> <script src="script.js"> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | <ul> <li ng-repeat="tab in data"> <input type='checkbox' ng-click='change($index,confirm)' ng-model='confirm' /> {{tab.name}} </li> </ul> {{val}} var app = angular.module('app', []); app.controller('MainCtrl',function($scope){ $scope.val=[]; $scope.confirm=false; $scope.data=[ { name:'vijay' }, { name:'krishna' },{ name:'Nikhil' } ]; $scope.temp; $scope.change=function(index,confirm){ console.log(confirm); if(!confirm){ ($scope.val).push($scope.data[index]); } else{ $scope.temp=$scope.data[index]; var d=($scope.val).indexOf($scope.temp); if(d!=undefined){ ($scope.val).splice(d,1); } } } }) |
看看这个:清单模型。
它可以与JavaScript数组和对象一起使用,并且可以使用静态HTML复选框,而无需ng repeat
1 2 3 4 | <label><input type="checkbox" checklist-model="roles" value="admin"> Administrator</label> <label><input type="checkbox" checklist-model="roles" value="customer"> Customer</label> <label><input type="checkbox" checklist-model="roles" value="guest"> Guest</label> <label><input type="checkbox" checklist-model="roles" value="user"> User</label> |
而javascript方面:
1 2 3 4 | var app = angular.module("app", ["checklist-model"]); app.controller('Ctrl4a', function($scope) { $scope.roles = []; }); |
一种简单的HTML唯一方法:
1 2 3 4 5 6 7 8 9 10 11 12 | <input type="checkbox" ng-checked="fruits.indexOf('apple') > -1" ng-click="fruits.indexOf('apple') > -1 ? fruits.splice(fruits.indexOf('apple'), 1) : fruits.push('apple')"> <input type="checkbox" ng-checked="fruits.indexOf('orange') > -1" ng-click="fruits.indexOf('orange') > -1 ? fruits.splice(fruits.indexOf('orange'), 1) : fruits.push('orange')"> <input type="checkbox" ng-checked="fruits.indexOf('pear') > -1" ng-click="fruits.indexOf('pear') > -1 ? fruits.splice(fruits.indexOf('pear'), 1) : fruits.push('pear')"> <input type="checkbox" ng-checked="fruits.indexOf('naartjie') > -1" ng-click="fruits.indexOf('apple') > -1 ? fruits.splice(fruits.indexOf('apple'), 1) : fruits.push('naartjie')"> |
使用@umur kontac的这个例子?,我认为在整个其他对象/数组中使用捕获选定的数据,例如编辑页。
数据库中的catch选项切换某个选项例如,下面的所有颜色json:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | { "colors": [ { "id": 1, "title":"Preto - #000000" }, { "id": 2, "title":"Azul - #005AB1" }, { "id": 3, "title":"Azul Marinho - #001A66" }, { "id": 4, "title":"Amarelo - #FFF100" }, { "id": 5, "title":"Vermelho - #E92717" }, { "id": 6, "title":"Verde - #008D2F" }, { "id": 7, "title":"Cinza - #8A8A8A" }, { "id": 8, "title":"Prata - #C8C9CF" }, { "id": 9, "title":"Rosa - #EF586B" }, { "id": 10, "title":"Nude - #E4CAA6" }, { "id": 11, "title":"Laranja - #F68700" }, { "id": 12, "title":"Branco - #FFFFFF" }, { "id": 13, "title":"Marrom - #764715" }, { "id": 14, "title":"Dourado - #D9A300" }, { "id": 15, "title":"Bordo - #57001B" }, { "id": 16, "title":"Roxo - #3A0858" }, { "id": 18, "title":"Estampado" }, { "id": 17, "title":"Bege - #E5CC9D" } ] } |
两类数据对象,一个对象的
在数据库中选择了两项:
1
2
3
4
5
6
7
8
9
10
11
12
13
14[{"id":12,"title":"Branco - #FFFFFF
<hr>
<p>
I've put an array in the controller.
</p>
[cc lang="javascript"]$scope.statuses = [{ name: 'Shutdown - Reassessment Required' },
{ name: 'Under Construction' },
{ name: 'Administrative Cancellation' },
{ name: 'Initial' },
{ name: 'Shutdown - Temporary' },
{ name: 'Decommissioned' },
{ name: 'Active' },
{ name: 'SO Shutdown' }]在标记上,我放置了如下内容
1
2
3
4<input type="checkbox" name="unit_status" ng-model="$scope.checkboxes[status.name]"> {{status.name}}
{{$scope.checkboxes}}输出如下,在控制器中,我只需要检查它是真是假;检查为真,不存在/不检查为假。
1
2
3
4
5
6
7{
"Administrative Cancellation":true,
"Under Construction":true,
"Shutdown - Reassessment Required":true,
"Decommissioned":true,
"Active":true
}希望这有帮助。
试试我的宝贝:
**
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23myApp.filter('inputSelected', function(){
return function(formData){
var keyArr = [];
var word = [];
Object.keys(formData).forEach(function(key){
if (formData[key]){
var keyCap = key.charAt(0).toUpperCase() + key.slice(1);
for (var char = 0; char<keyCap.length; char++ ) {
if (keyCap[char] == keyCap[char].toUpperCase()){
var spacedLetter = ' '+ keyCap[char];
word.push(spacedLetter);
}
else {
word.push(keyCap[char]);
}
}
}
keyArr.push(word.join(''))
word = [];
})
return keyArr.toString();
}
})**
然后,对于任何带有复选框的NG模型,它将返回一个包含您选择的所有输入的字符串:
1
2
3
4
5
6
7
8<label for="Heard about ITN">How did you hear about ITN?: *</label>
<label class="checkbox-inline"><input ng-model="formData.heardAboutItn.brotherOrSister" type="checkbox">Brother or Sister</label>
<label class="checkbox-inline"><input ng-model="formData.heardAboutItn.friendOrAcquaintance" type="checkbox">Friend or Acquaintance</label>
{{formData.heardAboutItn | inputSelected }}
//returns Brother or Sister, Friend or Acquaintance我认为下面的方法对于嵌套的NG重复更清晰和有用。在普朗克上看看。
引用此线程:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17<html ng-app="plunker">
<head>
Test
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js">
</head>
<body ng-controller="MainCtrl">
{{tab.name}}
<input type="checkbox" ng-change="checkValues()" ng-model="val.checked"/>
[cc lang="javascript"] {{selected}}var app=angular.module('plunker',[]);app.controller('mainctrl',函数($scope,$filter){$scope.mytab页=[{姓名:"Tab1",价值观:值:"value1",选中:假,值:"value2",选中:假,值:"value3",选中:假,值:"value4",选中:假]}{姓名:"Tab2",价值观:值:"value1",选中:假,值:"value2",选中:假,值:"value3",选中:假,值:"value4",选中:假]}]$scope.selected=[]$scope.checkValues=函数()。{Angular.ForEach($scope.myTabs,函数(值,索引){var selecteditems=$filter('filter')(value.values,选中:真);角度.forEach(selecteditems,函数(值,索引){$scope.selected.push(值);(});(});console.log($scope.selected);};(});<正文>