将服务用于View AngularJS

Nor*_*isz 21 angularjs angularjs-service

我有angularJS服务的问题.

我有简单的服务:

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;
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

然后我有一个简单的控制器

.controller('NavbarTopCtrl', ['$scope','$modal','AuthService',function($scope,$modal,authService) {
    $scope.authService=authService;  //IS good practice?
    console.log($scope);
}])
Run Code Online (Sandbox Code Playgroud)

我无法将我的服务用于View.我做了简单的技巧,工作正常.

$scope.authService=authService
Run Code Online (Sandbox Code Playgroud)

但是如何在我的视图(HTML文件)中调用Service而不使用它?

lua*_*sus 19

在视图中使用服务通常是一种不好的做法.视图应仅包含表示逻辑.在您的示例中,您可以尝试仅传递用户对象,而不是将整个服务传递给视图.例如$scope.currentUser = authService.currentUser().

  • myApp.configure(function($ rootScope){$ rootScope.foo = function(){console.log("来自世界各地叫我;)")}); (13认同)
  • 当你有一组你希望通过"ng-click"之类的东西从视图中调用的函数时怎么办?将您想要暴露的每个函数包装在控制器内的调用函数内部是非常繁琐的.思考? (10认同)
  • `$ scope.currentUser`是否绑定到`authService.currentUser()`中的更改? (3认同)