J'ai un problème avec le service angularJS.
J'ai un service simple:
angular.module('mainApp.services', []).factory('AuthService',
function ($http) {
//var currentUser = null;
//var authorized = false;
//AutoLogin for testing
var currentUser={email: "[email protected]", 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;
}
};
});
alors j'ai un simple contrôleur
.controller('NavbarTopCtrl', ['$scope','$modal','AuthService',function($scope,$modal,authService) {
$scope.authService=authService; //IS good practice?
console.log($scope);
}])
Je ne peux pas utiliser mon service dans View. J'ai fait un truc simple et ça marche bien.
$scope.authService=authService
Mais comment appeler le service sans cela dans ma vue (fichier HTML)?
L'utilisation de services à l'intérieur des vues est généralement une mauvaise pratique. La vue ne doit contenir qu'une logique de présentation. Dans votre exemple, au lieu de transmettre l'intégralité du service à la vue, vous pouvez essayer de ne transmettre qu'un objet utilisateur. Par exemple $scope.currentUser = authService.currentUser()
.