【AngularJS系列】基于angular-ui-select定制下拉框多选

背景:希望有个下拉多选框,显示一个店铺的属性,其属性值类似于,如下表示: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>-->
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值