AngularJS在$rootScope和$scope之间进行选择

AngularJS choosing between $rootScope and $scope

本文关键字:行选 之间 选择 rootScope AngularJS scope      更新时间:2023-09-26

我有一个应用程序,其中前端是建立在AngularJS和后端是在laravel 5.1。

用户身份验证由帐户控制器通过API调用完成:

myApp.controller('LoginCtrl', function($scope,$auth,$location){
        $scope.authenticate = function(provider){
            $auth.authenticate(provider)
            .then(function() {
                  toastr.success('You have successfully signed in with ' + provider);
                  $location.path('/');
                })
                .catch(function(response) {
                  toastr.error(response.data.message);
                });
            };
});

angular.module('MyApp')
    .factory('Account', function($http){
        return {
            getProfile: function(){
                 return $http.get('/api/me');
            }
        }
    });

一旦认证,getProfile函数被调用,控制器将用户数据填充到视图中:

myApp.controller('UserApiCtrl', function($scope,$auth,Account){
    $scope.user = {};
    $scope.getProfile = function(){
        Account.getProfile()
            .then(function(response){
                $scope.user = response.data;
            })
            .catch(function(response){
            })
    };
    $scope.getProfile();
})  

对于页面能够在所有不同的控制器上呈现用户数据,我应该将用户数据分配给$scope还是将其分配给app.js中的$rootScope,其中用户数据将在全局可用

你可以使用$cookies("提供对浏览器cookies的读/写权限")

  myApp.controller('UserApiCtrl', function($scope,$auth,Account,Auth,$cookies){
        $scope.user = {};
        $scope.getProfile = function(){
            Account.getProfile()
                .then(function(response){
                    $cookies.putObject('user', response.data);
                })
                .catch(function(response){
                    if(response.status === 401)
                        $cookies.remove('user');
                })
        };
        $scope.getProfile();
    })  
  • 示例服务:

        myApp.factory('Auth', ['$rootScope', '$cookies', function($rootScope, $cookies) {
            $rootScope.user = $cookies.getObject('user') || {
                id: '',
                token: ''
            };
    

我在我的body标签上使用了一个控制器来提供对更多全局内容的访问,然后在我的各个视图中的控制器来做更特定于视图的事情。

<body ng-controller = "appController as app">
<div ui-view></div>
</body>

对我来说,这似乎比使用$rootScope更干净。