gpt4 book ai didi

javascript - 隔离每个 Controller 的 Angular 服务

转载 作者:行者123 更新时间:2023-11-28 06:55:50 24 4
gpt4 key购买 nike

我使用 Angular 服务来放置我在任何地方使用的常用代码。它有效,但现在我发现了一些奇怪的事情!服务中的变量在 Controller 之间共享,如果我在一个页面中有两个 Controller ,如果一个 Controller 更改变量,它会影响其他 Controller 。

但我不想要它!我需要一个类似服务的系统,但每个 Controller 都有一个隔离的环境。有什么办法吗?

更新:

app.service("myService",function(){
this.variable = 1;
});

app.controller("loginCtrl",function($scope,myService){
console.log(myService.variable); //prints 1
myService.variable++;
});

app.controller("signupCtrl",function($scope,myService){
console.log(myService.variable); //prints 2
});

我需要每个 Controller 使用一个新的 myService(isolated)

最佳答案

AngularJS 中的所有服务都是单例的。因此,任何注入(inject)的单例都可能受到另一个 Controller 的影响。也就是说,您还可以故意创建注入(inject)服务的新实例,只要您不将共享服务注入(inject)到实例化服务中,这将保证隔离范围。

HTML:

<div ng-app="app">
<div ng-controller="loginCtrl">
</div>
<div ng-controller="signupCtrl">
</div>
</div>

JS:

var app = angular.module('app', []);

app.controller("loginCtrl", ['$scope', 'sharedService', function($scope, sharedService){
var myService = sharedService.getInstance();
console.log(myService.variable); //prints 1
myService.variable++;
}]);

app.controller("signupCtrl", ['$scope', 'sharedService', function($scope, sharedService){
var myService = sharedService.getInstance();
console.log(myService.variable); //prints 1
}]);

app.factory('sharedService', [function () {
return {
getInstance: function () {
return new instance();
}
}

function instance () {
this.variable = 1;
}
}]);

Fiddle

关于javascript - 隔离每个 Controller 的 Angular 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32574680/

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