选择自定义指令和ng-change

Select custom directive and ng-change

本文关键字:ng-change 指令 自定义 选择      更新时间:2023-09-26

使用带有自定义指令的<select>,我想在值改变时运行一个函数。

html

<select name="user_type" ng-model="user_type" user-type ng-change="check_type()">
指令

gb_dash.directive('userType', function(){
    return{
        restrict: 'A',
        require: '^ngModel',
        scope:{
            check_type: '&'
        },
        link: function(scope, elem, attrs){
            scope.check_type = function(){
                console.log('changed');
            }
        }
    }
});

由于您有一个隔离作用域,因此您的check_typeng-change表达式不在同一作用域中。你也不希望这样。

相反,ng-model提供了一种向ngModel.$viewChangeListeners注册侦听器的方法-这正是ngChange指令使用的-挂钩到视图模型更改事件。

require: "ngModel",
scope: { }, // to mimic your directive - doesn't have to be isolate scope
link: function(scope, element, attrs, ngModel){
   ngModel.$viewChangeListeners.push(function(){
     console.log('changed');
   }
}

由于您的隔离作用域,您可以包含对$parent的调用来实现您的结果。

link: function(scope, elem, attrs) {
    scope.$parent.check_type = function() {
        console.log('changed');
    }
}

但是,调用$parent可能不适合您的情况。

或者你可以放弃ng-change,而把$watch换成ngModel。这可以这样完成…

link: function(scope, elem, attrs, ngModel) {
    scope.$watch(function() {
        return ngModel.$modelValue;
    }, function(newValue, oldValue) {
        console.log('model value changed...', newValue, oldValue);
    }, true);
}

JSFiddle Link - $parent demo

JSFiddle Link - $watch demo