gpt4 book ai didi

javascript - 在 AngularJS 中在哪里监听事件和操作 DOM(编译、链接)?

转载 作者:行者123 更新时间:2023-11-30 17:34:28 25 4
gpt4 key购买 nike

app.directive('appView', ['appService',function($scope) {   

return {
restrict : '',
template : '',
templateUrl : 'app/app.html',
controller : function($scope,docsService){

},
compile : function(tElement, tAttrs, transclude){
tElement.bind('click', function() {
console.log("In compile");
//Update DOM element
});

},
//or
/*
link : function(scope, element, attrs) {
element.bind('click', function() {
console.log("In link");
//Update DOM element.
});
},*/


};

}]);

我正在探索 AngularJS,发现编译和链接不能一起工作,
现在,要操作 DOM 并监听事件,这里的最佳实践是什么,使用链接还是编译?为什么选择一个而不是另一个?链接有一个范围属性,我想可以更灵活。

最佳答案

从 Angular docs on $compile :

The compile function deals with transforming the template DOM. Since most directives do not do template transformation, it is not used often. Examples that require compile functions are directives that transform template DOM, such as ngRepeat, or load the contents asynchronously, such as ngView.

和:

The link function is responsible for registering DOM listeners as well as updating the DOM. It is executed after the template has been cloned. This is where most of the directive logic will be put.

所以在大多数情况下,link 功能就足够了。如有必要,您可以添加监听器并操作 DOM。 compile 函数对于更“极端”的情况是必需的,比如 ng-repeat。 (根据我使用 Angular 约 14 个月的经验统计,我只使用过一次 compile。)

顺便说一句(再次来自文档):

A compile function can have a return value which can be either a function or an object.

  • returning a (post-link) function - is equivalent to registering the linking function via the link property of the config object when the compile function is empty.

  • returning an object with function(s) registered via pre and post properties - allows you to control when a linking function should be called during the linking phase. See info about pre-linking and post-linking functions below.

关于javascript - 在 AngularJS 中在哪里监听事件和操作 DOM(编译、链接)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22324583/

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