我是angularjs的新手,我正在尝试编写一些指令,这些指令可以用于某些事件,比如'blur'.但我对事件指令的后端进程感到困惑.它是如何工作的?有许多指令,如'ngClick'或'ngHover',我们将要在该事件上执行的方法传递给此指令.像这样:
<div ng-click="doSomethingOnClick()"></div>
Run Code Online (Sandbox Code Playgroud)
我们在控制器中定义'doSomethingOnClick()'方法.现在我只想知道'ngClick'指令如何在事件发生时执行此方法.如果你能用代码解释,那就太好了.
提前致谢.
这里是从1.1.5源代码中提取的ng-click的定义我还在整个代码中添加了注释来解释每行我据了解.
/**
* @ngdoc directive
* @name ng.directive:ngClick
*
* @description
* The ngClick allows you to specify custom behavior when
* element is clicked.
*
* @element ANY
* @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
* click. (Event object is available as `$event`)
*
* @example
<doc:example>
<doc:source>
<button ng-click="count = count + 1" ng-init="count=0">
Increment
</button>
count: {{count}}
</doc:source>
<doc:scenario>
it('should check ng-click', function() {
expect(binding('count')).toBe('0');
element('.doc-example-live :button').click();
expect(binding('count')).toBe('1');
});
</doc:scenario>
</doc:example>
*/
/*
* A directive that allows creation of custom onclick handlers that are defined as angular
* expressions and are compiled and executed within the current scope.
*
* Events that are handled via these handler are always configured not to propagate further.
*/
//make an object
var ngEventDirectives = {};
//for each string in the list separated by spaces
forEach(
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave'.split(' '),
//create a function which creates the directive and is called for each element in the list above
function(name) {
//directiveNormalize does things to strip the -data prefix and deal with camel casing conversion
var directiveName = directiveNormalize('ng-' + name);
//setting a property on the ngEventDirectives equal to a new [] which contains the dependency injection values and finally the function that will return the directive definion object (or in this case the link function) $parse service is being used
ngEventDirectives[directiveName] = ['$parse', function($parse) {
//link function to call for each element
return function(scope, element, attr) {
//$parse the value passed in the quotes for this attribute ng-click="something()" then fn = something()
//my guess is parse does some magic... will investigate this soon
var fn = $parse(attr[directiveName]);
//Setup the regular event listener using bind as an abstraction for addEventListener/attachEvent
element.bind(lowercase(name), function(event) {
//running the function
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}];
}
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2009 次 |
| 最近记录: |