angularjs用于下拉列表的嵌套级联指令

时间:2017-02-08 11:01:06

标签: angularjs angularjs-directive

我想创建一个级联下拉指令。

<my-dropdown label="states" url="http://statelisturl">    
   <my-dropdown label="cities" url="http://citylisturl">
   </my-dropdown>
</my-dropdown>

但是,当我选择州城市将从网址获取时,州将首先列出。

这在技术上是否适用于angularjs?或者我应该为每个下拉列表分别指示?

1 个答案:

答案 0 :(得分:0)

你可以这样做:

.directive("myDropdown", function() {
    return {
        restrict: "E",
        require: ["myDropdown", "?^^myDropdown"],
        template: "<select ng-options='opt as opt.label for opt in $ctrl.options' ng-model='$ctrl.selectedOption' ng-change='$ctrl.changed($ctrl.selectedOption)'></select><div ng-transclude></div>",
        scope: true,
        bindToController: {
            url: "@",
            label: "@"
        },
        controller: function($scope, $http) {
            var _self = this;
            _self.init = function() {
                $http.get(_self.url).then(function(response) {
                    _self.options = response.data;
                });
            }
            _self.parentChanged = function(item) {
                var id = item.id;
                $http.get(_self.url + "?id=" + id).then(function(response) {
                    _self.options = response.data;
                });
            }
        },
        link: function(scope, element, attrs, ctrls) {
            var ctrl = ctrls[0];
            var parentCtrl = ctrls[1];

            if (parentCtrl) {
                scope.$watch(function() {
                    return parentCtrl.selectedOption;
                }, function(newval) {
                    if (newval) {
                        ctrl.parentChanged(newval);
                    }
                });
            } else {
                ctrl.init();
            }
        },
        controllerAs: "$ctrl",
        transclude: true
    }
});

编辑:我有一个工作示例here