AngularJs,更改用户是否连接的菜单项

时间:2014-04-27 11:20:40

标签: angularjs authentication angularjs-directive navbar

我是AngularJS的新手,我尝试处理用户身份验证。

我确保非连接用户无法访问受限制的路由:

app.js

  .config(function ($routeProvider) {
    $routeProvider
        .when('/myroute', {
          templateUrl: 'views/myroute.html',
          controller: 'MyrouteCtrl',
            access: {
                isFreeAccess: false
            }
        })
 ...
 .run( function ($rootScope, $location, Auth) {

    $rootScope.$on('$routeChangeStart', function(currRoute, prevRoute){

        if (prevRoute.access != undefined) {
            // if route requires auth and user is not logged in
            if (!prevRoute.access.isFreeAccess && !Auth.isLogged) {
                // redirects to index
                $location.path('/');
            }
        }

AuthService.js

.factory('Auth', function () {
    var user;

    return{
        setUser : function(aUser){
            user = aUser;
        },
        isLoggedIn : function(){
            return(user)? user : false;
        }
    }
});

login.js

$scope.login = function(user) {

    $http({
        url: ***,
        method: "POST",
        data: user,
        headers: {'Content-Type': 'application/json'}
    }).success(function (data, status, headers, config) {
            $scope.persons = data;

            Auth.setUser(data); //Update the state of the user in the app

            $location.path("/");
    }).error(function (data, status, headers, config) {
        $scope.status = status;
    });

用户状态在他连接时存储。现在我想在导航栏中显示新项目。

的index.html

<div ng-include src="'views/navbar.html'"></div>

navbar.js

.controller('NavbarCtrl', function ($scope) {
    $scope.items = [
        {'name': 'Home', "needAuthentication": false},
        {'name': 'About', "needAuthentication": false},
        {'name': 'Settings', "needAuthentication": true},
        {'name': 'Logout', "needAuthentication": true}
    ];
});

navbar.html

<div ng-controller="NavbarCtrl" class="collapse navbar-collapse navbar-ex1-collapse" role="navigation">
        <ul class="nav navbar-nav navbar-right">
            <li ng-repeat="item in items ">
               <a ng-if="item.needAuthentication == false || (item.needAuthentication == true && Auth.isLoggedIn())" href="#{{item.name}}">{{item.name}}</a> 
            </li>
        </ul>
    </div>

当用户启动应用时:

1)他尚未连接

ng-if="item.needAuthentication == false || (item.needAuthentication == true && Auth.isLoggedIn ())"

&#39;首页&#39;和&#39;关于&#39;项目显示。

2)然后他连接到应用程序,但导航栏不会被其他项目重新渲染(&#39;设置&#39;&#39;退出&#39;)。

实现这一目标的正确方法是什么?使用指令/将其绑定到模型/或其他东西?

事先提前

1 个答案:

答案 0 :(得分:1)

我认为isLoogged函数应该在定义user时返回true

尝试更改

return(user)? user : false;

return(user)? true : false;