背景:希望有个下拉多选框,显示一个店铺的属性,其属性值类似于,如下表示:0001(十进制为1)表示店铺属性1,0010表示店铺属性2,以此类推。若某店铺属性为0011(十进制表示为3),则其同时具有属性1和属性2
直接上代码
一、index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="UTF-8">
<title>webapp</title>
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">
</head>
<body>
<div ng-controller ="appCtrl">
<shop-flag-select ng-model="flag"></shop-flag-select>
<pre>
{{flag}}
</pre>
</div>
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
<script src="bower_components/angular-ui-select/dist/select.js"></script>
<link href="bower_components/angular-ui-select/dist/select.css" rel="stylesheet">
<script src="comp/shopFlagSelect.js"></script>
<script>
angular.module('app', ['ui.select', 'ngSanitize','shopflagselect'])
.controller('appCtrl',function ($scope) {
$scope.flag = '3';
});
</script>
</body>
</html>
说明:使用bower依次安装 bootstrap、angularjs、angularjs-ui-select、angular-sanitize
二、自定义组件
var module = angular.module('shopflagselect', []);
module.directive('shopFlagSelect',function () {
return{
restrict : 'E',
templateUrl : 'comp/shopFlagSelect.html',
scope:{
flagValue : '=ngModel'
},
link:function (scope,element,attrs) {
scope.itemArray =[
{id: 1, name: '担保交易'},
{id: 10, name: '货到付款'},
];
scope.selected = {
value:[ ]
};
// 转换flag属性到下拉框的选项
attrs.$observe('ngModel', function (value) {
var target = scope.flagValue;
$.each(scope.itemArray, function (index, result) {
//将下拉选项的id字符串转换为2进制数
var itemValue = parseInt(result.id,2);
if( target & itemValue){
scope.selected.value.push(result);
}
});
});
//下拉多选时,及时计算flag属性
scope.$watch('selected',function(newValue,oldValue) {
var flag = 0;
$.each(scope.selected.value, function (index, result) {
flag = flag + parseInt(result.id, 2);
});
scope.flagValue = flag;
},true);
}
}
});
三、模板
<ui-select multiple ng-model="selected.value">
<ui-select-match placeholder="Select person...">
{{$item.name}}
</ui-select-match>
<ui-select-choices repeat="item in (itemArray | filter: $select.search) track by item.id">
<span ng-bind="item.name"></span>
</ui-select-choices>
</ui-select>
<!--<pre>-->
<!--{{selected.value}}-->
<!--</pre>-->