[英]Angularjs - set limit on user choice in a select field
我正在尝试建立一种方法来限制几个选择字段中的用户选择。 下面是一个示例,这是一个jsfiddle- http://jsfiddle.net/HB7LU/18414/
HTML:
<div ng-controller="MyCtrl">
<select size="5" id="selectpicker1" multiple ng-model="params.monthly" ng-change="selectionChanged(params.monthly)">
<option ng-repeat="month in newMonthlyArray">{{month}}</option>
</select>
</div>
控制器:
var myApp = angular.module('myApp', []);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.name = 'Superhero';
//console.log('YES');
$scope.newMonthlyArray = ["2015-Jan", "2015-Feb", "2015-Mar", "2015-Apr"];
$scope.selectionChanged = function (data) {
if (data.length > 2) {
alert('You can choose 2 months');
}
}
}
我遇到的问题是删除最后选择的选项并更新$scope
变量。 我可以使用JQuery,但不想创建混合解决方案。
任何想法将不胜感激!
您可以在选择元素中获得对额外选择的项目的引用,然后取消选择这些项目。 在selectionChanged
方法中,遍历select元素中的选项,取消选择无效的选择,然后更新模型( data
是对params.monthly
的引用)。
angular.forEach(document.getElementById("selectpicker1").options, function(item) {
if (data.length > 2 && item.selected) {
data.splice(2);
item.selected = false;
}
});
您可以使用$ watch服务使事情变得更轻松,并删除自己的watch方法( selectionChanged
):
$scope.$watch(function() {
// In this function, return whatever object/value you would like to observe.
// This function is invoked whenever there is a change to the specified value/obj
return document.getElementById("selectpicker1").options;
}, function (items) {
// The argument of this function holds the new value of what you return in the
// first function. Feel free to name it whatever you wish
angular.forEach(items, function(item) {
var data = $scope.params.monthly;
if (data.length > 2 && item.selected) {
data.splice(2);
item.selected = false;
alert('You can choose 2 months');
}
});
});
通常,您需要清除/取消注册您的watch函数,但在这种情况下,您不需要这样做,因为没有其他方法/函数依赖于select元素的值。
您实际上不必做很多事情即可删除额外选择的元素:
if(data.length > 2){
data.splice(2);
//alert('You can choose 2 months');
}
基本上,这就是您所需要的: data
是您的ng-model="params.monthly"
并且由于此模型已绑定到select元素,因此Angular会进行其余工作来更新它:
http://jsfiddle.net/HB7LU/18420/
编辑:如@Metallica建议,并非在所有情况下Angular都会更新select元素。
提供视觉反馈的唯一方法是手动更新DOM:
if(data.length > 2) {
data.splice(2);
var selected = select.querySelectorAll('option:checked');
angular.forEach(selected, function(s) {
if(data.indexOf(s.value) < 0) s.selected = false;
});
}
在更新的示例中, select
是$element[0].querySelector('select')
此控制器中的select元素。
附加代码用于:
selected
属性 更新的小提琴: http : //jsfiddle.net/HB7LU/18422/
将此添加到您的控制器:
$scope.onSelect = function() {
var selected = this.month;
$scope.newMonthlyArray.splice($scope.newMonthlyArray.indexOf(selected), 1);
};
这是您的标签:
<option ng-click="onSelect()" ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.