AngularJS检查选择的选项(带过滤器)是否已更改

时间:2016-10-28 13:01:36

标签: angularjs angularjs-directive

我有一个自定义指令,它被限制为属性,并且对select元素起作用以使它们更具样式(使用jquery select-bootstrap)。

目前还没有正确的方法来检查/观看选择过滤器的选项是否已更改。

e.g。

<label>First Select</label>
<select ng-model="vm.myFirstModel"
  ng-options="hour.id as hour.label for hour in vm.hours" selectpicker> </select>

<label>Second Select</label>
<select ng-model="vm.mySecondModel"
  ng-options="hour.id as hour.label for hour in vm.hours | filter:vm.filterHours(vm.myFirstModel)" selectpicker>
</select>

我的指示

angular.module('VAdmin.theme')
        .directive('selectpicker', selectpicker);

    /** @ngInject */
    function selectpicker() {
        return {
            restrict: 'A',
            require: '?ngOptions',
            priority: 1500, // make priority bigger than ngOptions and ngRepeat
            link: {
                pre: function(scope, elem, attrs) {
                    elem.append('<option data-hidden="true" disabled value="">' + (attrs.title || 'Select something') + '</option>')
                },
                post: function(scope, elem, attrs) {
                    function refresh() {
                        elem.selectpicker('refresh');
                    }

                    if (attrs.ngModel) {
                        scope.$watch(attrs.ngModel, refresh);
                    }

                    if (attrs.ngDisabled) {
                        scope.$watch(attrs.ngDisabled, refresh);
                    }

                    elem.selectpicker({
                        dropupAuto: false,
                        hideDisabled: true
                    });
                }
            }
        };
    }

当我的ng-options改变时(使用过滤器)

,我需要运行refresh()

1 个答案:

答案 0 :(得分:1)

您可以创建要在第二个选择器中使用的模型表:

<select ng-model="vm.mySecondModel"
    model-watch="vm.myFirstModel"
    ng-options="hour.id as hour.label for hour in vm.hours | filter:vm.filterHours(vm.myFirstModel)" selectpicker>

然后,请注意:

if (attrs.modelWatch) {
    scope.$watch(attrs.modelWatch, refresh);
}