2015-04-05 86 views
0

免責聲明:這是一個正在進行的「第一個項目」Angular,所以我仍然在切齒。AngularJS子模塊(和認證)

長話短說,我使用the answer here作爲認證模式(通過RESTful調用PHP腳本完成)。它工作得很好。當我希望它與事物的角度方面已經存在的控制器一起工作時,警告就出現了。來自我的C++/Perl/Python背景,我想寫一次幷包含它。爲此,我找到了the answer here。雖然它不完全適合我。對於初學者來說,我的網站是從另一個網站模板化的,而且語法有點不同 - 我還沒有弄清楚。當我在myApp中嘗試InjectedModule.otherApp時,出現錯誤。該代碼看起來是這樣的:

angular.module('otherApp', ['ngRoute','infinite-scroll']) 
.controller("loginController", 
      ['$scope', 
      '$http', 
      '$location', 
      '$window', 
      function($scope,$http,$location,$window) { 
// Do a bunch of authentication stuff 

}]) 

angular.module('myApp', ['ngRoute','infinite-scroll']) 
.controller("imageController", 
     ['$scope', 
     '$http', 
     '$location', 
     '$window', 
     function($scope,$http,$location,$window) { 

// Guts of the page generated here 

}]) 

理想情況下,我想在imageController依賴認證控制器,當然有過什麼是基於認證顯示的控制。

回答

3

控制器不應該依賴。你應該爲此使用服務。 首先,你應該建立一個認證服務。

angular.module('authentication') 
.service('authService', function(){ 
    var isAuthenticated = false; 
    var user  = 'guest'; 
    var username = ''; 

    return { 
     login: function() { isAuthenticated = true; }, 
     isAuthenticated: function() { return isAuthenticated; }, 
     loggedInUser: function() { return user; } 
    } 
}); 

現在,你的控制器可以從這項服務中調用驗證邏輯:

angular.module('authentication', ['ngRoute','infinite-scroll']) 
.controller("loginController", 
     ['$scope', '$http', '$location', '$window', 'authService', 
     function($scope,$http,$location,$window, authService) { 

    // Do a bunch of authentication stuff 
    $scope.login = function LoginUser() { 
    authService.login(); 
    } 

}]); 

// include 'authentication' module - 'images' module will depend on it 
angular.module('images', ['ngRoute','infinite-scroll', 'authentication']) 
.controller("imageController", 
    ['$scope', '$http', '$location', '$window', 'authService', 
    function($scope,$http,$location,$window, authService) { 

    // Guts of the page generated here 
    $scope.loadImages = function LoadImages() { 
    if (authService.isAuthenticated()) { 
     // do authenticated user image load logic 
    } else { 
     // do unauthenticated user image load logic 
    } 
    } 
}]); 

你的應用程序還應該包括兩個模塊:

angular.module('bootstraper', [ 
    'authentication', 
    'images' 
]) 
+0

謝謝 - 我在工作我,但現在當我回家時,我會修補這個。 – 2015-04-06 12:13:29

+0

終於到了這裏。服務部分是否會出現語法錯誤?我在第一個代碼塊中出現錯誤。隨意看看這裏:http://www.gamengai.com/authtest.html 我沒有機會陷入比這更遠的地方。 – 2015-04-11 14:59:40

+0

您需要在創建第一個服務/控制器時初始化模塊... 您需要更改控制器/服務的順序,首先添加控制器,因爲它定義了模塊'angular.module( '認證',['ngRoute','無限滾動'])。控制器,然後還定義一個服務... – 2015-04-11 15:02:41