[英]How to get selected checkboxes on button click in angularjs
我想做这样的事情
<input type="checkbox" ng-model="first" ng-click="chkSelect()"/><label>First</label>
<input type="checkbox" ng-model="second" ng-click="chkSelect()"/><label>Second</label>
<input type="checkbox" ng-model="third" ng-click="chkSelect()"/><label>Third</label>
<input type="checkbox" ng-model="forth" ng-click="chkSelect()"/><label>Forth</label>
<button>Selected</button>
在按钮上,单击我要显示所选复选框的标签名。
$scope.chkSelect = function (value) {
console.log(value);
};
由于复选框是映射的,因此您可以在chkSelect()函数中引用$ scope.first,$ scope.second等。 也可以将一组复选框映射为单个数据数组,而不必为每个复选框命名。 如果您正在生成复选框(可能是从一组数据中生成),这将很方便。
我同意Bublebee Mans解决方案。 您已经遗漏了很多关于为什么要获得标签的详细信息。 无论如何,如果您真的想要得到它,可以这样做:
$scope.chkSelect = function (value) {
for(var key in $scope){
var inputs = document.querySelectorAll("input[ng-model='" + key + "']");
if(inputs.length){
var selectedInput = inputs[0];
var label = selectedInput.nextSibling;
console.log(label.innerHTML);
}
};
};
您可以把它弄乱看看是否确实选中了它。
小提琴: http : //jsfiddle.net/pzz6s/
旁注,对于任何知道棱角的人,请原谅我。
您希望控制器中具有以下内容(未经测试,从内存中工作):
$scope.checkBoxModels = [ { name: 'first', checked: false }, { name: 'second', checked: false }, { name: 'third', checked: false }, { name: 'fourth', checked: false } ];
然后在您看来:
<input ng-repeat"checkboxModel in CheckBoxModels" ng-model="checkBoxModel.checked" ng-click="chkSelect(checkBoxModel)" /><label>{{checkBoxModel.name}}</label>
然后更新您的功能:
$scope.chkSelect = function (checkBoxModel) {
console.log(checkBoxModel.name);
};
如果要处理服务器数据,则可能需要隔离的html块并仅在控制器中处理数据。
您可以通过在控制器中创建数组(可能是响应中的数据)并使用ngRepeat指令在html代码中进行独立处理来实现。
这是我告诉你的:
HTML:
<form ng-controller="MyCtrl">
<label ng-repeat="name in names" for="{{name}}">
{{name}}
<input type="checkbox"
ng-model="my[name]"
id="{{name}}"
name="favorite" />
</label>
<div>You chose <label ng-repeat="(key, value) in my">
<span ng-show="value == true">{{key}}<span>
</label>
</div>
</form>
使用Javascript
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.names = ['pizza', 'unicorns', 'robots'];
$scope.my = { };
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.