使用服务进入 View AngularJS [英] Use service into View AngularJS

查看:18
本文介绍了使用服务进入 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 文件)中没有这个的情况下调用 Service?

推荐答案

在视图中使用服务通常是一种不好的做法.视图应该只包含一个表示逻辑.在您的示例中,您可以尝试仅传递一个用户对象,而不是将整个服务传递给视图.例如 $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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆