【问题标题】:Injecting service variable to Directives将服务变量注入指令
【发布时间】:2016-02-12 04:10:05
【问题描述】:

所以我遇到了一些麻烦。我已经查看了Injecting service to Directive 以前的所有解决方案,但我真的不知道我做错了什么。我有一个如下所示的 authServices。

app.factory('authService', ['$http', function ($http) {

var authServiceFactory = {};

var _authentication = {
    isAuth: false,
    userName: ""
};
var _login = function (loginData) {
_authentication.isAuth = true;
_authentication.userName = loginData.userName;
}
appFactory.login = _login;
return appFactory;
}]);

我通过他们提出的方法注入它。

    app.directive('headerNotification', ['authService', function (authService) {
    return {
        templateUrl: 'app/scripts/directives/header/header-notification/header-notification.html',
    restrict: 'E',
    replace: true,
    link: function (scope) {
        scope.authService = authService;
    }
    }
}]);

我的html是这样的

    <li data-ng-hide="authentication.isAuth">

我真的觉得我做错了。任何帮助将不胜感激。

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-service angularjs-injector


    【解决方案1】:

    你认为authentication.isAuth是什么。

    我认为你错过了拼写你的对象。

    <li data-ng-hide="authService.isAuth">
    

    您的作用域对象是authService 而不是authentication,对吧?

    更新 - 将验证传递给指令

    我假设你的控制器中有你的 auth 变量。

    $scope.myAuthService = authservice;
    

    不,您可以将此变量作为属性传递给您的指令。

    <header-notification my-auth="myAuthService"> </header-notification>
    

    这里myAuthService是一个作用域变量。

    更改您的指令以接受此变量,

    app.directive('headerNotification', function () {
        return {
                    templateUrl: 'app/scripts/directives/header/header-notification/header-notification.html',
                    restrict: 'E',
                    scope : {
                                myAuth : '=' // here you specify that you need to convert your attribute variable 'my-auth' to your directive's scope variable 'myAuth'
                            },
                    replace: true,
                    link: function (scope, element, attr, controller) {
                          // here you will get your auth variable
                          scope.myAuth; // this contains your auth details
                    }
                }
    });
    

    【讨论】:

    • 所以对象是 authService,带有一个变量 _authentication.isAuth。这个对象应该被注入到我认为可能做错的指令中。当我使用 data-ng-hide 时,它​​不应该是对象的变量吗?
    • @JuliusDoan,您可以将您的 auth 变量作为参数传递给该指令。
    • 很抱歉让我感到困惑,但请您指导我完成这件事吗?猜猜这是问题的基础,哈哈。
    • @JuliusDoan,检查我的答案的更新。如果您有任何疑问,请告诉我。
    • 伟大的作品,我唯一需要做的就是将控制器添加到指令中。
    猜你喜欢
    • 2014-02-08
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    相关资源
    最近更新 更多