Внедрение сервисной переменной в директивы

Так что у меня немного проблем. Я просмотрел все предыдущие решения от инъекционного обслуживания до директивы, но я действительно понятия не имею, что я делаю неправильно. У меня есть 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">

Я действительно чувствую, что просто делаю это неправильно. Любая помощь будет принята с благодарностью.

1 ответ

Решение

Что такое authentication.isAuth по вашему мнению.

Я думаю, что вы скучаете по буквам вашего объекта.

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

Ваш объект области видимости authService не authentication, право?

Обновление - Передайте veraible директиве

Я предполагаю, что у вас есть переменная 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
                }
            }
});
Другие вопросы по тегам