【问题标题】:Why is $event not working with ng-change? [duplicate]为什么 $event 不能与 ng-change 一起使用? [复制]
【发布时间】:2017-08-25 13:17:25
【问题描述】:

这是我的 html 标签,它有 ng-change 事件,我将 $event 作为 arg 传递给它。

 <input type="text" ng-model="dynamicField.value" ng-change="myFunction(dynamicField,$event)"/>

下面是我的angularJS函数-

$scope.myFunction=function(dynamicField,event){
alert(event);
}

每当调用此函数时,警报都会将事件的值显示为“未定义”。

请指导我。

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

angular.jsngChange 指令注册一个

当输入因用户而改变时执行的 Angular 表达式 与输入元素的交互。

该指令只是将评估的表达式添加到视图更改侦听器列表中,

var ngChangeDirective = valueFn({
  restrict: 'A',
  require: 'ngModel',
  link: function(scope, element, attr, ctrl) {
    ctrl.$viewChangeListeners.push(function() {
      scope.$eval(attr.ngChange);
    });
  }
});

一旦$modelValue 更新,这些侦听器将一次执行一个,

this.$$writeModelToScope = function() {
    ngModelSet($scope, ctrl.$modelValue);
    forEach(ctrl.$viewChangeListeners, function(listener) {
      try {
        listener();
      } catch (e) {
        $exceptionHandler(e);
      }
    });
  };

如您所见,没有任何事件被传递,因为 ngChange 所做的只是在更新 ngModel 时执行表达式。这是确保您的表达式在模型值设置后运行的好方法。

ngChange 不同,ngClick$event 传递给点击处理函数,因为它处理的是 DOM 事件,

forEach(
  'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  function(eventName) {
    var directiveName = directiveNormalize('ng-' + eventName);
    ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
      return {
        restrict: 'A',
        compile: function($element, attr) {
          // We expose the powerful $event object on the scope that provides access to the Window,
          // etc. that isn't protected by the fast paths in $parse.  We explicitly request better
          // checks at the cost of speed since event handler expressions are not executed as
          // frequently as regular change detection.
          var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
          return function ngEventHandler(scope, element) {
            element.on(eventName, function(event) {
              var callback = function() {
                fn(scope, {$event:event});
              };
              if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
                scope.$evalAsync(callback);
              } else {
                scope.$apply(callback);
              }
            });
          };
        }
      };
    }];
  }
);

您会看到,在事件发生时,DOM 事件对象以$eventfn(scope, {$event:event}); 的形式传递给处理函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    相关资源
    最近更新 更多