在用户登录AngularJS上更改html标头的最佳方法

时间:2016-01-24 05:25:21

标签: html angularjs header angular-ng-if

我正在处理一个Angular应用程序,其中主页面(角度模块初始化的位置)有一个标题,我想在用户登录时显示不同的div。

这是index.html的标题代码片段:

<header ng-controller="HeaderController">
    <div class="container">
        <div class="row">
            <div class="col-lg-12 col-xs-12">
                <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 none">
                    <a class="navbar-brand" href="#page-top"><img src="Content/img/logo.png" class="img-responsive" alt="logo"></a>
                </div>
                <div class="col-lg-3 col-md-3 col-sm-3 col-xs-4 col-lg-offset-6 col-md-offset-6 col-sm-offset-9" ng-if="showloginheader">
                    <!--ng-if="showloginheader"-->
                    <span href="#" class="button-login" id="toggle-login" ng-click="OnLoginClick()">Ingresar</span><img src="Content/img/logo.png" id="logo_min" alt="logo">
                    <div id="login" ng-controller="LoginController">
                        <form name="loginForm" ng-submit="login()" role="form">
                            <input type="text" placeholder="Ingresá el usuario" required ng-model="username" />
                            <input type="password" placeholder="Ingresá la contraseña" required ng-model="password" />
                            <!--<input type="submit" class="login" value="Ingresar" />-->
                            <input type="checkbox" id="checkbox" checked><div class="reco-contra">Recordar contraseña</div>
                            <div class="olvi-contra"><a>Olvidaste la contraseña?</a></div>
                            <!--<div class="form-actions">-->
                            <input type="submit" class="login" value="Ingresar" /> <!-- ng-disabled="form.$invalid || vm.dataLoading" -->
                            <input type="submit" id="clase-fb" value="Ingresar con Facebook" />
                            <input type="submit" id="clase-tw" value="Ingresar con Twitter" />
                            <input type="submit" id="clase-goo" value="Ingresar con Google" />
                            <div class="olvi-contra"><a>Olvidaste la contraseña?</a></div>
                        </form>
                        <a href="#/register"><input type="submit" value="&iexcl;Registrate ahora!" /></a>
                    </div>
                </div>
                <div class="col-lg-3 col-md-3 col-sm-3 col-xs-4 col-lg-offset-6 col-md-offset-6 col-sm-offset-9" ng-if="showcurrentuserheader"><!--ng-if="showcurrentuserheader"-->
                    <span href="#" class="log-img" id="toggle-login"><img src="img/fefe.png" alt="logo">Pablo</span>
                    <div id="login">
                        <div id="login-ok">
                            <div class="opcion-log">
                                <a href="recetas_obtenidas.html"><strong>RECETAS OBTENIDAS</a></strong>
                            </div>
                            <div class="opcion-log">
                                <a href="perfil.html"><i class="fa fa-cog fa-spin"></i>  PERFIL</a>
                            </div>
                            <div class="opcion-log">
                                <a href="#">CERRAR SESION</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</header>

您可以注意到徽标下方有两个div,我想要实现的是显示第一个div(具有&#34; ng-if = showloginheader&#34;)同时用户不是&# 39;登录然后在用户进入应用程序时显示另一个(具有&#34; ng-if = showcurrentuserheader&#34;)。

我想知道哪个是最好的选择,直到现在我已经尝试使用ng-if指令。

首先,我初始化变量抛出一个服务(使其可以被几个控制器访问):

(function () {
    'use strict';

    angular
        .module('iziCooker')
        .factory('UserService', UserService);

    UserService.$inject = ['$http'];
    function UserService($http) {
        var service = {};
        var showloginheader = true;
        var showcurrentuserheader = false;

        service.GetLoginHeaderState = GetLoginHeaderState;
        service.GetCurrentUserHeaderState = GetCurrentUserHeaderState;
        service.ChangeHeadersVisibility = ChangeHeadersVisibility;

        return service;

                function GetLoginHeaderState() {
                return showloginheader;
            }

            function GetCurrentUserHeaderState() {
                return showcurrentuserheader;
            }

            function ChangeHeadersVisibility() {
                showloginheader = false;
                showcurrentuserheader = true;
            }

    }
})();

然后我在HeaderController中分配这些值:

    (function () {
    'use strict';

    angular
        .module('iziCooker')
        .controller('HeaderController', HeaderController);

    HeaderController.$inject = ['$scope', 'UserService'];
    function HeaderController($scope, UserService) {
        $scope.showloginheader = UserService.GetLoginHeaderState();
        $scope.showcurrentuserheader = UserService.GetCurrentUserHeaderState();

    }

})();

到目前为止,这是正常的,因为HeaderController在应用程序启动时被注入(它位于&#34;主页面&#34; Angular,index.html)。

但是当我从数据库获得成功的响应进入应用程序后,我尝试更改登录控制器中的变量值。

    (function () {
    'use strict';

    angular
        .module('iziCooker')
        .controller('LoginController', LoginController);

    LoginController.$inject = ['$location', 'AuthenticationService', 'FlashService', '$scope', 'UserService'];
    function LoginController($location, AuthenticationService, FlashService, $scope, UserService) {
        $scope.dataLoading = false;
        $scope.username = "";
        $scope.password = "";

        console.log("Login Controller Loaded!");

        //vm.login = login;

        (function initController() {
            // reset login status
            AuthenticationService.ClearCredentials();
        })();

      $scope.login =  function login() {
          $scope.dataLoading = true;
          AuthenticationService.Login($scope.username, $scope.password, function (response) {
                if (response.success) {
                    AuthenticationService.SetCredentials($scope.username, $scope.username);
                    UserService.ChangeHeadersVisibility();
                    $location.path('/map');
                } else {
                    FlashService.Error(response.message);
                    $scope.dataLoading = false;
                }
            });
      };

    }

})();

当我被重定向到&#34; / map&#34;看来,它仍然显示第一个div。似乎那些ng-if变量没有更新或类似的东西。也许我错过了一些东西。

我几乎可以肯定这不是这样做的方式,所以我想知道我是否必须改变某些内容或完全改变代码。

谢谢。

编辑:

身份验证服务

    (function () {
    'use strict';

    angular
        .module('iziCooker')
        .factory('AuthenticationService', AuthenticationService);

    AuthenticationService.$inject = ['$http', '$cookieStore', '$rootScope', '$timeout', 'UserService'];
    function AuthenticationService($http, $cookieStore, $rootScope, $timeout, UserService) {
        var service = {};

        service.Login = Login;
        service.SetCredentials = SetCredentials;
        service.ClearCredentials = ClearCredentials;

        return service;

        function Login(username, password, callback) {

            /* Dummy authentication for testing, uses $timeout to simulate api call
             ----------------------------------------------*/
            //$timeout(function () {
            //    var response;
            //    UserService.GetByUsername(username)
            //        .then(function (user) {
            //            if (user !== null && user.password === password) {
            //                response = { success: true };
            //            } else {
            //                response = { success: false, message: 'Username or password is incorrect' };
            //            }
            //            callback(response);
            //        });
            //}, 1000);

            /* Use this for real authentication
             ----------------------------------------------*/
            $http.post('ws/api/Usuario/Login', { username: username, password: password })
                .success(function (response) {
                    callback(response);
                });

        }

        function SetCredentials(username, password) {
            var authdata = Base64.encode(username + ':' + password);

            $rootScope.globals = {
                currentUser: {
                    username: username,
                    authdata: authdata
                }
            };

            $http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; // jshint ignore:line
            $cookieStore.put('globals', $rootScope.globals);
        }

        function ClearCredentials() {
            $rootScope.globals = {};
            $cookieStore.remove('globals');
            $http.defaults.headers.common.Authorization = 'Basic';
        }
    }

    // Base64 encoding service used by AuthenticationService
    var Base64 = {

        keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',

        encode: function (input) {
            var output = "";
            var chr1, chr2, chr3 = "";
            var enc1, enc2, enc3, enc4 = "";
            var i = 0;

            do {
                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);

                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;

                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                } else if (isNaN(chr3)) {
                    enc4 = 64;
                }

                output = output +
                    this.keyStr.charAt(enc1) +
                    this.keyStr.charAt(enc2) +
                    this.keyStr.charAt(enc3) +
                    this.keyStr.charAt(enc4);
                chr1 = chr2 = chr3 = "";
                enc1 = enc2 = enc3 = enc4 = "";
            } while (i < input.length);

            return output;
        },

        decode: function (input) {
            var output = "";
            var chr1, chr2, chr3 = "";
            var enc1, enc2, enc3, enc4 = "";
            var i = 0;

            // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
            var base64test = /[^A-Za-z0-9\+\/\=]/g;
            if (base64test.exec(input)) {
                window.alert("There were invalid base64 characters in the input text.\n" +
                    "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
                    "Expect errors in decoding.");
            }
            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

            do {
                enc1 = this.keyStr.indexOf(input.charAt(i++));
                enc2 = this.keyStr.indexOf(input.charAt(i++));
                enc3 = this.keyStr.indexOf(input.charAt(i++));
                enc4 = this.keyStr.indexOf(input.charAt(i++));

                chr1 = (enc1 << 2) | (enc2 >> 4);
                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                chr3 = ((enc3 & 3) << 6) | enc4;

                output = output + String.fromCharCode(chr1);

                if (enc3 != 64) {
                    output = output + String.fromCharCode(chr2);
                }
                if (enc4 != 64) {
                    output = output + String.fromCharCode(chr3);
                }

                chr1 = chr2 = chr3 = "";
                enc1 = enc2 = enc3 = enc4 = "";

            } while (i < input.length);

            return output;
        }
    };

})();

2 个答案:

答案 0 :(得分:3)

实现类似这样的事情的最佳方法是在AuthenticationService中设置/取消设置用户对象。然后,您可以设置范围变量,如$scope.authentication,并使ng-if(或ng-show)依赖于用户对象。

由于您在$ rootScope中设置用户模型,因此您可以在任何地方使用它。

$rootScope.globals = {
  currentUser: {
    username: username,
    authdata: authdata
  }
};

因此,在您的标记中,您将获得未登录标题:

<div ... ng-hide="$root.globals.currentUser"> 

对于登录标题:

<div ... ng-show="$root.globals.currentUser">

答案 1 :(得分:0)

您还可以尝试ng-showng-hide

HTML

<h1 ng-show="toggleHeader">First header</h1>
    <h1 ng-hide="toggleHeader">Second header</h1>

JavaScript

$scope.toggleHeader = true; //false to switch header.

虽然问题出在其他地方。尝试在HTML中编写{{showloginheader}},看看它是否确实在true / false之间发生了变化。

相关问题