簡體   English   中英

AngularJS在$ rootScope和$ scope之間選擇

[英]AngularJS choosing between $rootScope and $scope

我有一個應用程序,其中前端在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(“提供對瀏覽器cookie的讀/寫訪問權限。”)

  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更干凈。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM