gpt4 book ai didi

javascript - 具有自己作用域的函数之间的通信

转载 作者:行者123 更新时间:2023-11-29 23:35:05 24 4
gpt4 key购买 nike

我正在开发一个网站,其中的一部分(页面生成器)是由另一个人编写的。这部分代码在模板缓存中准备它的 HTML,并有几个函数可以访问这个 HTML 页面中的复杂小部件。每个复杂的小部件都有自己的 Controller 作为独立的功能。代码的形式是:

(function (app) {
try {
app = angular.module(SGGenerator + '.templates');
} catch (error) {
app = angular.module(SGGenerator + '.templates', []);
}

app.run(["$templateCache", function ($templateCache) {
$templateCache.put("ivm-color-picker/templates/color-picker-field.html",
"<label class=\"item item-input item-has-button-right\">\n" +
[…]
"</a>");
}]);
})();
(function () {
var controllerName = 'ServerController', moduleName = 'ivmServer';

angular.module(moduleName, ['ionic'])
.controller(controllerName, function ($scope) {
[…]
$scope.startPage2Server = function ($scope) {
[…]
};
}).directive(moduleName, function () {
[…]
}
})
}()); // ServerController
(function () {
var controllerName = 'IconPickerController', moduleName = 'ivmIconpicker';

angular.module(moduleName, ['ionic'])
.controller(controllerName, function ($scope, $ionicPopover, $http) {
[…]
})
.directive(moduleName, function () {
return {
controller: controllerName,
restrict: 'E',
scope: {
ngModel: '=',
label: '@'
},
templateUrl: 'ivm-icon-picker/templates/icon-picker-field.html'
}
})
}()); // IconPickerController

等我需要的是它们的“通用范围”之类的东西,以便可以轻松进行数据交换。你对这个问题的解决方案是什么?我不想与服务器通信以获取某些“全局”变量内容。

最佳答案

AngularJS 框架内的通信使用服务的概念进行,它们代表 Controller 之间的共享资源,以执行数据交换和业务逻辑。

您可以按如下方式添加您的服务:

angular.module(moduleName, ['ionic'])
.factory('MyService', function() {
let myVar = 1;
return {
setMyVar: function(value) {
myVar = value;
},
getMyVar: function() {
return myVar;
}
};
});

您现在可以在您的 Controller 中使用此注册服务:

angular.module(moduleName, ['ionic'])
.controller(controllerName, function ($scope, MyService) {
MyService.setMyVar(2);
})

// ...

angular.module(moduleName, ['ionic'])
.controller(otherControllerName, function ($scope, MyService) {
MyService.getMyVar();
})

关于javascript - 具有自己作用域的函数之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46489190/

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