简体   繁体   English

AngularJS使用$ rootscope的最佳实践?

[英]AngularJS Best practices to use $rootscope?

I'm a beginner in angular and I try to do this tutorial ( http://sahatyalkabov.com/create-a-tv-show-tracker-using-angularjs-nodejs-and-mongodb/ ) 我是angular的初学者,我尝试做一下本教程( http://sahatyalkabov.com/create-a-tv-show-tracker-using-angularjs-nodejs-and-mongodb/

I use the best practices by John Papa. 我使用John Papa的最佳做法。 So, i don't use $scope but a variable. 因此,我不使用$ scope而是一个变量。 var vm = this; var vm = this; on my controller and ui-router. 在我的控制器和ui路由器上。

But on this tutorial, at one moment, he use $rootScope. 但是在本教程中,他一时使用$ rootScope。 I have seen that it's bad practice but sometimes you have to use. 我已经看到这是不好的做法,但有时您必须使用。

On this tutorial, have you another possibility without $rootScope or you haven't choice? 在本教程中,如果没有$ rootScope,是否还有其他选择?

Thanks ! 谢谢 !

I quickly checked the link and noted that $rootScope is used to hold the currentUser property. 我迅速检查了链接,并注意到$ rootScope用于保存currentUser属性。 This kind of things are better with services and factories, I try not to use $rootScope at all, though the temptation is strong. 对于服务和工厂来说,这种情况会更好,尽管诱惑很强烈,但我尽量不使用$ rootScope。

You're right, that using of $rootScope is not a good practice. 没错,使用$rootScope不是一个好习惯。

As I understand, in this tutorial he uses $rootScope just for storing currentUser on login (and remove on logout ). 据我了解,在本教程中,他使用$rootScope仅用于在login存储currentUser (并在logout删除)。 That's it. 而已。

And this case could be easily implemented without using $rootScope at all. 而且这种情况很容易实现,根本不用$rootScope It will require a bit more code, but it's not so difficult. 它将需要更多的代码,但这并不困难。

If you ok to write a bit more code and make you code without using bad practices then you can do something the following: 如果您可以编写更多代码并使您不使用不良做法进行编码,则可以执行以下操作:

You can create a separated service: 您可以创建一个单独的服务:

angular.module('MyApp')
       .service('UserKeeper', function($) {
           var userKeeper = {
               currentUser:{}
           };

           return userKeeper;
        });

and then just inject this service in your Auth factory and save your user in currentUser property instead of saving it in your $rootScope . 然后只需将此服务注入您的Auth工厂中,并将您的用户保存在currentUser属性中,而不是将其保存在$rootScope

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM