gpt4 book ai didi

angularjs - Angular 可重用函数

转载 作者:行者123 更新时间:2023-12-01 23:02:50 25 4
gpt4 key购买 nike

我有几个指令需要在完成任务后调用相同的函数。该函数需要访问主 Controller 作用域,同时还需要修改 DOM。该函数应该如何以及在哪里声明?

最佳答案

您应该使用服务,服务可以访问 $rootScope,尽管最好将 DOM 修改保留在指令级别,但在某些情况下您可以这样做。

angular.module("myModule", [])
.factory("MyService", function ($rootScope) {
return {
myFunction: function () { // do stuff here }
}
})
.directive("MyDirective", function (MyService) {
return {
link: function (scope, iElement, iAttrs) {
// try do keep dom modification here, you have access to MyService,
// let it do the algorithm and try to keep dom modification here.
// PS: you can also inject $rootScope to directives.
};
};
});

关于angularjs - Angular 可重用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14852963/

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