2016-05-17 20 views
2

如何從不同的文件(使用不同的模塊)獲取$ scope變量?例如,我有兩個文件 - index.jslogin.js,我想從login.js獲得用戶名index.js。我試圖使用服務,但無法實現該目標。控制器沒有在另一個角度文件中看到服務。如何從不同的AngularJS文件獲取變量?

代碼部分給出如下:

bookApp.controller('bookListCtrl', ['sharedProperties', function($scope, $http, sharedProperties) { 
'use strict'; 


$scope.name = "Alice"; 



console.log("in book controller"); 

console.log("getting login name: "+sharedProperties.getProperty()); 

var authentication = angular.module('authentication', []); 


authentication.service('sharedProperties', function() { 
        var property = 'First'; 

        return { 
         getProperty: function() { 
          return property; 
         }, 
         setProperty: function(value) { 
          property = value; 
         } 
        }; 
}); 

我得到這個例外 -

angular.min.js:63 Error: Unknown provider: authentication.sharedPropertiesProvider <- authentication.sharedProperties at Error (native) at

+0

在聲明其他模塊時,是否包含對模塊「身份驗證」的依賴關係? – Sarathy

+0

你如何在你的主應用程序中包含身份驗證模塊?不要忘記你需要將它包含在你的整個模塊中。所以你的主應用程序需要包含「身份驗證」作爲一個模塊。 – PeterS

+0

@Sarathy我包含了其他模塊,並得到了不同的例外。目前,它不能識別「身份驗證」模塊中的服務,並將其顯示爲「未定義」。 – RaufA

回答

0

在給定的實現有2個問題。第一個問題是模塊的「認證」需要成爲消費模塊的依賴。第二個問題是在bookListCtrl的聲明中。它需要被定義如下。

bookApp.controller('bookListCtrl', ['$scope','$http','sharedProperties', function($scope, $http, sharedProperties){ 
}]); 
0

你能給您如何使用服務的例子嗎?

一般來說,如果你定義的控制器,如:

app.controller('LoginController', ['UserService', function($scope) { 
    $scope.someMethod = function(){ 
     // push information to service 
     UserService.username = $scope.username; 
    } 
}]); 

app.controller('IndexController', ['UserService', function($scope) { 
    // pull information from service 
    $scope.username = UserService.username; 
}]); 

它應該工作。我必須建議你使用Controller而不是$ scope。更多的信息在這裏:https://docs.angularjs.org/api/ng/directive/ngController

相關問題