angularJs 下拉选择指令(directive)

使用anguarlJs 实现的的一个select 选择指令,可传入绑定值

/*
 * author rufeng
 * data 2017-10-18
 * email [email protected]
 * 使用方法 
 * <>
 */
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:""};
                    }
                };
            }
        };
    });

你可能感兴趣的:(angularJs 下拉选择指令(directive))