这是我的 html 标签,其中包含 ng-change 事件,我将 $event 作为参数传递给它。
<input type="text" ng-model="dynamicField.value" ng-change="myFunction(dynamicField,$event)"/>
下面是我的 angularJS 函数-
$scope.myFunction=function(dynamicField,event){
alert(event);
}
每当调用此函数时,警报都会将事件的值显示为“未定义”。
请指导我。
最佳答案
来自 angular.js
, ngChange
指令注册一个
Angular expression to be executed when input changes due to user interaction with the input element.
该指令只是将计算后的表达式添加到 View 更改监听器列表中,
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 事件对象被传递到处理函数中,如 $event
, fn(scope, {$event:event});
。
关于javascript - 为什么 $event 不能与 ng-change 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43137772/