Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use service into View AngularJS

Tags:

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: "[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;         }     }; }); 

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)?

like image 333
Norbert Pisz Avatar asked Aug 22 '13 09:08

Norbert Pisz


1 Answers

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().

like image 131
luacassus Avatar answered Oct 29 '22 08:10

luacassus