简体   繁体   中英

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/ )

I use the best practices by John Papa. So, i don't use $scope but a variable. var vm = this; on my controller and ui-router.

But on this tutorial, at one moment, he use $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?

Thanks !

I quickly checked the link and noted that $rootScope is used to hold the currentUser property. This kind of things are better with services and factories, I try not to use $rootScope at all, though the temptation is strong.

You're right, that using of $rootScope is not a good practice.

As I understand, in this tutorial he uses $rootScope just for storing currentUser on login (and remove on logout ). That's it.

And this case could be easily implemented without using $rootScope at all. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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