angularJs 下拉选择指令(directive)
2017-11-09 本文已影响26人
如风_周
使用anguarlJs 实现的的一个select 选择指令,可传入绑定值
<div class="address-select-item">
<select class="form-control" ng-model="selectedItem" ng-options="item.name for item in datalist" ng-change="itemChange()">
<option value="" ng-bind="defaultTitle"></option>
</select>
</div>
/*
* author rufeng
* data 2017-10-18
* email rufeng.zhou@qq.com
* 使用方法 <rufeng-selected datalist="a" selected-item="b" default-title="c"></rufeng-selected>
* <>
*/
angular.module('rufengSelected', [])
.directive("rufengSelected", function() {
return {
restrict: 'EA',
scope: {
datalist: '=', // 传入的数组
selectedItem: '=',//绑定的选择值 (obj)
defaultTitle: '@',//要显示的默认信息
},
templateUrl: 'Selected_tpl.html', //html文件(上面那个html)
link: function(scope, elem, attrs) {
if (scope.defaultTitle == undefined) {
scope.defaultTitle = "请选择";
}
scope.$watch("datalist", function(newValue, oldValue, scope) {
if (newValue.length > 0) {
if (scope.selectedItem == null||scope.selectedItem.value == null) {
scope.selectedItem = { value: "" };
} else{
var i = 0,
len = scope.datalist.length || 0;
for (i = 0; i < len; i++) {
if (scope.selectedItem.value == scope.datalist[i].value) {
scope.selectedItem = scope.datalist[i];
}
}
}
}
});
scope.itemChange =function () {
if(scope.selectedItem == null){
scope.selectedItem = {value:""};
}
};
}
};
});