gpt4 book ai didi

angularjs - 传递给 angularjs 事件指令的方法如何工作?

转载 作者:行者123 更新时间:2023-12-02 07:02:39 24 4
gpt4 key购买 nike

我是 angularjs 的新手,我正在尝试编写一些指令,这些指令将适用于某些事件,例如“模糊”。但我真的对事件指令的后端过程感到困惑。它是如何工作的?有许多指令,如“ngClick”或“ngHover”,我们将要在该事件上执行的方法传递给该指令。像这样:

<div ng-click="doSomethingOnClick()"></div>

然后我们在 Controller 中定义了“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});
});
});
};
}];
}
);

关于angularjs - 传递给 angularjs 事件指令的方法如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17751704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com