【问题标题】:Use service into View AngularJS在 View AngularJS 中使用服务
【发布时间】:2013-08-24 23:48:58
【问题描述】:

我对 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;
        }
    };
});

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

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

我无法在 View 中使用我的服务。我做了简单的把戏,效果很好。

$scope.authService=authService

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

【问题讨论】:

    标签: angularjs angularjs-service


    【解决方案1】:

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

    【讨论】:

    • 看这里登录服务。它工作正常。 github.com/robertjchristian/angular-enterprise-seed
    • 如果你有一组函数想要通过ng-click 之类的方式从视图中调用呢?将您想要暴露给视图的每个函数都包装在控制器内的调用者函数中是非常乏味的。想法?
    • myApp.configure(function($rootScope) { $rootScope.foo = function() { console.log("从任何地方给我打电话;)") });
    • $scope.currentUser 是否绑定到 authService.currentUser() 的更改?
    猜你喜欢
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 2015-06-15
    • 2020-02-29
    • 2015-10-07
    • 2017-11-22
    相关资源
    最近更新 更多