使用服务进入View AngularJS [英] Use service into View AngularJS
本文介绍了使用服务进入View AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对angularJS服务有疑问.
I have issue with angularJS Service.
我的服务很简单
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;
}
};
});
然后我有一个简单的控制器
then I have a simple Controller
.controller('NavbarTopCtrl', ['$scope','$modal','AuthService',function($scope,$modal,authService) {
$scope.authService=authService; //IS good practice?
console.log($scope);
}])
我无法在View中使用我的服务.我做了简单的把戏,并且工作正常.
I can't use my service into View. I made simple trick and works fine.
$scope.authService=authService
但是如何在视图(HTML文件)中不带此调用服务?
推荐答案
在视图内部使用服务通常是一种不好的做法.
该视图应仅包含表示逻辑.
在您的示例中,您可以尝试仅传递用户对象,而不是将整个服务传递给视图.例如$scope.currentUser = authService.currentUser()
.
Using services inside the views is generally a bad practice.
The view should contain only a presentation logic.
In your example instead of passing the whole service to the view you could try to pass only a user object. For example $scope.currentUser = authService.currentUser()
.
这篇关于使用服务进入View AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文