我遇到了angularJS服务的问题。
我的服务很简单:
angular.module('mainApp.services', []).factory('AuthService',
function ($http) {
//var currentUser = null;
//var authorized = false;
//AutoLogin for testing
var currentUser={email: "example@example.com", id: "15"};
var authorized=true;
// initial state says we haven't logged in or out yet...
// this tells us we are in public browsing
var initialState = false;
return {
initialState:function () {
return initialState;
},
login:function (userData) {
//Call API Login
currentUser = userData;
authorized = true;
initialState = false;
},
logout:function () {
currentUser = null;
authorized = false;
},
isLoggedIn:function () {
return authorized;
},
currentUser:function () {
return currentUser;
},
authorized:function () {
return authorized;
}
};
});
然后我有一个简单的控制器
.controller('NavbarTopCtrl', ['$scope','$modal','AuthService',function($scope,$modal,authService) {
$scope.authService=authService; //IS good practice?
console.log($scope);
}])
我无法将我的服务用于View。我做了一个简单的技巧,工作正常。
$scope.authService=authService
但是如何在我的视图(HTML文件)中调用没有此服务的服务?
答案 0 :(得分:19)
在视图中使用服务通常是一种不好的做法。
视图应仅包含表示逻辑。
在您的示例中,您可以尝试仅传递用户对象,而不是将整个服务传递给视图。例如$scope.currentUser = authService.currentUser()
。