Use service into View AngularJS

心不动则不痛 提交于 2019-12-09 07:53:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!