这是我的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);
}
无论何时调用此函数,警报都会将事件的值显示为“未定义”。
请指导我。
答案 0 :(得分:2)
从angular.js
,ngChange
指令注册
当输入因用户而发生变化时要执行的角度表达式 与输入元素的交互。
该指令只是将计算后的表达式添加到视图更改侦听器列表中,
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});
传递到处理函数中。