使用Angular JS的自定义指令

时间:2015-09-22 03:57:49

标签: angularjs angularjs-directive

在我的html中,我已经包含了这样的指令。

<login ng-show="!authService.authenticated"></login>

指令

angular.module('XXXXX').directive("login", function () {
    return {
        restrict: "E",
        scope: {
            authenticated: '='
        },
        transclude: true,
        replace: false,
        templateUrl: "views/layouts/login.html",
        controller: function ($scope, AuthService) { 
            $scope.authService = AuthService;
            $scope.authService.authenticated = false;

            $scope.authService.authenticated = AuthService.isAuthenticated();

            $scope.login = function () {
                var username = angular.element.find("[name='username']"),
                    password = angular.element.find("[name='password']"),
                    results = null;                            

                username = $(username).val();                        
                password = $(password).val();                               
                results = AuthService.login(username, password);
                if (results.status != "failed"){
                    $scope.authService.authenticated = true;    
                }                
            }; 
            console.log($scope.authService.authenticated);     
        },
        link: function (scope) {
        }
    }
});

登录服务和身份验证通过AuthService正常工作,但问题是一旦成功登录完成我仍然无法隐藏登录html集。请有人帮我解决这个问题。

感谢。

2 个答案:

答案 0 :(得分:0)

使用$ rootScope而不是$ scope.authService

angular.module('XXXXX').directive("login", function () {
return {
    restrict: "E",
    scope: {
        authenticated: '='
    },
    transclude: true,
    replace: false,
    templateUrl: "views/layouts/login.html",
    controller: function ($scope,$rootScope, AuthService) { 
        $rootScope.authService = AuthService;
        $rootScope.authService.authenticated = false;

        $rootScope.authService.authenticated = AuthService.isAuthenticated();

        $scope.login = function () {
            var username = angular.element.find("[name='username']"),
                password = angular.element.find("[name='password']"),
                results = null;                            

            username = $(username).val();                        
            password = $(password).val();                               
            results = AuthService.login(username, password);
            if (results.status != "failed"){
                $rootScope.authService.authenticated = true;    
            }                
        }; 
        console.log($rootScope.authService.authenticated);     
    },
    link: function (scope) {
    }
}

});

答案 1 :(得分:0)

当您在隔离范围中声明authenticated变量时,您应该通过从指令属性传递它来修改该范围变量,然后您可以轻松地在指令控制器内使用authenticated变量,make {{1当用户被授权时,则为true,否则将为false。

<强>标记

authenticated

<强>指令

<login authenticated="authenticated" ng-show="!authenticated"></login>