【问题标题】:Select custom directive and ng-change选择自定义指令和 ng-change
【发布时间】:2015-09-25 09:52:52
【问题描述】:

<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');
            }
        }
    }
});

【问题讨论】:

    标签: javascript html angularjs angularjs-directive


    【解决方案1】:

    由于您有一个隔离范围,因此您的 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');
       }
    }
    

    【讨论】:

      【解决方案2】:

      由于您的隔离范围,您可以包括对$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 演示

      JSFiddle Link - $watch 演示

      【讨论】:

      • +1 您的 scope.$parent 让我好奇地尝试在我正在自定义和调用 ngChange 的指令上进行尝试。现在我需要了解什么是隔离作用域以及为什么直接作用域。$eval 不适用于隔离作用域。现在可以使用:link: function (scope, element, attrs, ngModel) { scope.doChange = function() { ngModel.$setDirty(); scope.$parent.$eval(attrs.ngChange); };
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 1970-01-01
      • 2015-08-15
      相关资源
      最近更新 更多