问题
I have issue with angularJS Service.
I have simple 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);
}])
I can't use my service into View. I made simple trick and works fine.
$scope.authService=authService
But how to call Service without this in my View (HTML file)?
回答1:
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()
.
来源:https://stackoverflow.com/questions/18377202/use-service-into-view-angularjs