AngularJS UI的路由器+国家需要帮助 [英] AngularJS UI-Router + State help needed

查看:168
本文介绍了AngularJS UI的路由器+国家需要帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的html code(code段1)及JS code(code段2)如下。
在HTML我包括谐音
并建立一个包含用户界面视图动态地改变HTML页面
当状态的变化。这是工作fine.The页面包含
页眉,页脚,左侧菜单,并基于状态的动态变化的内容。
现在我需要包括这个应用程序的登录页面。然而,我们并不需要
页眉,页脚,登录屏幕菜单。
目前,登录屏幕出现在页眉,页脚和菜单定义的单个用户界面视图。

我在想,如果我可以单独定义两个div一个用于登录,并显示该div如果状态登录。如果状态没有登陆然后显示在下面的HTML code所示格(片段1)。请告知,如果这是一个可行的思路。如果是的话请告知如何访问HTML中的状态。我试着用code(片段3)以下,但不能请告知。

进入状态

HTML(code段1):

 < code>
    < D​​IV CLASS =grandContainer>
    < D​​IV NG-包括=$ {}头'>< / DIV>
    < D​​IV CLASS =ABC>
            < D​​IV NG-包括=$ {}状态'>< / DIV>
            < D​​IV NG-包括=$ {菜单}'>< / DIV>
    < / DIV>
    < D​​IV CLASS =mainContainer上>
    <格UI的视图>< / DIV>
    < / DIV>    < p NG-包括=$ {}躯'>< / P>
< / DIV>
< / code>

JS(code段2):

 的app.config(['$ stateProvider','$ urlRouterProvider',函数($ stateProvider,$ urlRouterProvider){
    $ urlRouterProvider.otherwise('/登录');
    $ stateProvider.state(网格,{
    网址:'/网格,
    templateUrl:资源/ HTML / grid.html',
    控制器:'gridCtrl
    })。状态('chDetail',{
     网址:/ chDetail /:CHID
     templateUrl:资源/ HTML / chDetail.html
     控制器:'chDetailCtrl
     })状态(登录,{
     网址:/登录
     templateUrl:资源/ HTML / login.html的
     控制器:'loginCtrl
     });
     }])。控制器('gridCtrl',['$范围',函数($范围){
     $ scope.grid = [];
     }]);< / code>

code片段3: -

< code>< D​​IV NG秀={$ state.is('登录')}>项目< / DIV>
< / code>


解决方案

如果我理解正确的话,你要显示与出样页眉,页脚和放大器的其他视图登录视图;侧面菜单。

然后,你可以对你的看法布局创建一个抽象状态页脚侧面菜单等,并增加一个独立的国家为你的登录视图。

演示的棘手的部分是在抽象状态视图定义:

 摘要:真实,
观点:{
    '':{
        templateUrl:'的layout.html',
    },
    头@根':{
        模板:为标题的内容
    },
    页脚@根:{...}
}

什么是抽象状态干什么?的抽象状态将加载在未命名视图中的布局模板在主模板并加载,你想与孩子各国分享对方的意见。

根据需要每个孩子的状态就可以定义的内容视图中,并重新使用其他视图。

请看看下面的演示或本小提琴

注:
在演示登录当然是不安全的,只有在那里,以显示视图重定向处理。在您的应用程序,你有$ HTTP和的sessionStorage和令牌工作。

\r
\r

angular.module('demoApp',['ui.router'])\r
.RUN(函数($ rootScope,$州){\r
            $ rootScope。在$('$ stateChangeError',函数(EVT,于toParams,从,fromParams,错误){\r
          如果(error.redirectTo){\r
            $ state.go(error.redirectTo);\r
          }其他{\r
            $ state.go('错误',{状态:error.status})\r
          }\r
        })\r
    })\r
.factory('userService',userService)\r
的.config(路线);\r
\r
功能userService(){\r
VAR usersMock = {\r
    为testUser:{\r
        用户名:为testUser',\r
            密码:'1234'\r
        },\r
        testUser2:{\r
        用户名:testUser2',\r
            密码:'1234'\r
        }\r
    };\r
VAR userService = {\r
    用户:未定义,\r
    登录:功能(userCredentials){\r
        //后 - > $ http.post('权威性',userCredentials)。然后(...)\r
            //用于演示使用本地数据\r
            VAR用户= usersMock [userCredentials.username]\r
            userService.user =(用户放大器;及(user.password的== userCredentials.password))?\r
            用户:未定义;\r
            返回用户;\r
        },\r
        注销:功能(){\r
        userService.user =不确定;\r
        }\r
    }\r
    \r
    返回userService;\r
}\r
功能的路由($ urlRouterProvider,$ stateProvider){\r
\r
$ urlRouterProvider.otherwise('/');\r
    \r
    $ stateProvider\r
    .STATE('根',{\r
        网址:'',\r
        摘要:真实,\r
            解析:{\r
            用户:功能(userService){\r
                返回userService.user; //将异步在一个真正的应用\r
                }\r
            },\r
            观点:{\r
            '':{\r
                templateUrl:'的layout.html',\r
                },\r
            头@根':{\r
                模板:'< H1>头查看<跨度NG-IF =用户><按钮NG点击=退出()>退出< /按钮>< / SPAN><跨度NG-如果=&GT的用户!;<按钮NG点击=登录()>登录名和LT; /按钮>< / SPAN>< / H1>,\r
                    控制器:函数($范围,$状态,用户userService){\r
                    $ scope.user =用户;\r
                        $ scope.login =功能(){\r
                        $ state.go('登录');\r
                        };\r
                        $ scope.logout =功能(){\r
                        userService.logout();\r
                            $ state.go('root.home',{},{重装:真});\r
                        };\r
                    }\r
            },\r
                页脚@根':{\r
                    模板:'< P>页脚查看< / P>'\r
                }\r
            }\r
        })\r
    .STATE('root.home',{\r
            网址:'/',\r
            观点:{\r
                内容:{\r
                    模板:你好家\r
                }\r
            }\r
        })\r
        .STATE('root.about',{\r
            网址:'/约,\r
            观点:{\r
                内容:{\r
                    模板:有关视图\r
                }\r
            }\r
    })\r
        .STATE('root.restricted',{\r
            网址:'/受限制,\r
            解析:{\r
            AUTH:功能(userService,$ Q $超时){\r
                \r
                变种推迟= $ q.defer();\r
                / * //使用异步\r
                    返回UserService.load()。然后(功能(用户){\r
                      如果(permissionService.can(用户,{GOTO:状态})){\r
                        返回deferred.resolve({});\r
                      }其他{\r
                        返回deferred.reject({redirectTo:'some_other_state'});\r
                      }\r
                    } * /\r
                    \r
                   $超时(函数(){\r
                        如果(angular.isUndefined(userService.user)){\r
                            返回deferred.reject({redirectTo:'登录'});\r
                        }\r
                        其他{\r
                            返回deferred.resolve(userService.user);\r
                        }\r
                    });\r
                    \r
                    返回deferred.promise;\r
                }\r
            },\r
            观点:{\r
                内容:{\r
                    模板:这是登录后,才可见。您好{{用户}}!,\r
                    控制器:函数($范围,AUTH){\r
                    $ scope.user = auth.username;\r
                    }\r
                }\r
            }\r
    })\r
        .STATE('登陆',{\r
            网址:'/登录',\r
            templateUrl:意见/ login.html的,\r
            控制器:函数($范围,$状态,userService){\r
            $ scope.login =功能(CRED){\r
                VAR用户= userService.login(CRED)\r
                    \r
                    如果(angular.isUndefined(用户)){\r
                    警报('用户名或密码不正确。')\r
                    }\r
                    其他{\r
                    $ state.go('root.restricted');\r
                    }\r
                };\r
            }\r
        });\r
}

\r

&LT;脚本SRC =htt​​ps://ajax.googleapis.com/ajax /libs/angularjs/1.2.23/angular.min.js\"></script>\r
&LT;脚本src=\"https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.js\"></script>\r
\r
&LT; D​​IV NG-应用=demoApp&GT;\r
    &LT;一个UI的SREF =root.home的href =#&GT;家庭和LT; / A&GT;\r
    &LT;一个UI的SREF =root.about的href =#&gt;关于&LT; / A&GT;\r
    &LT;一个UI的SREF =root.restricted的href =#&GT;限制网页&LT; / A&GT;\r
    \r
    &LT;格UI的视图&gt;\r
    &LT; / DIV&GT;\r
    \r
    &LT;脚本类型=文/ NG-模板ID =意见/ login.html的&GT;\r
    &LT; H1&GT;登录和LT; / H1&GT;\r
        &LT; P&GT;尝试为testUser和1234凭证&LT; / P&GT;\r
        &LT;标签&gt;用户名和LT; /标签&gt;&LT;输入NG模型=userCred.username/&GT;\r
        &LT;标签&gt;密码和LT; /标签&gt;&LT;输入类型=密码NG模型=userCred.password/&GT;\r
        &LT;按钮NG点击=登录(userCred)&GT;登录和LT; /按钮&GT;\r
    &LT; / SCRIPT&GT;\r
    \r
    &LT;脚本类型=文/ NG-模板ID =的layout.html&GT;\r
    &LT; D​​IV&GT;\r
            &LT;格UI视图=头&GT;&LT; / DIV&GT;\r
            &LT;格UI视图=内容&GT;&LT; / DIV&GT;\r
            &LT;格UI视图=页脚&GT;&LT; / DIV&GT;\r
    &LT; / DIV&GT;\r
    &LT; / SCRIPT&GT;\r
&LT; / DIV&GT;

\r

\r
\r

I have html code (code snippet 1) & JS code (code snippet 2) as below. In html I am including the partials and building a page that contains a ui-view which dynamically changes the html when the state changes. This is working fine.The page contains a header , a footer , a left side menu and the dynamically changing content based on the state. Now I need to include a Login page for this application. However we don't need header , footer, menu for the login screen. Currently the login screen appears in the single ui-view defined along with header,footer and menu.

I was thinking if I could define two divs one for login alone and show that div if the state is login. If the state is not login then show the div shown in the html code below (snippet 1). Please advise if this is a feasible idea. If so please advise how to access the state in html. I tried to access the state using code (snippet 3) below but could not please advise.

html (code snippet 1) :

<code>
    <div class="grandContainer">    
    <div ng-include="'${header}'"></div>
    <div class="abc">
            <div ng-include="'${status}'"></div>
            <div ng-include="'${menu}'"></div>
    </div>      
    <div class="mainContainer">
    <div ui-view></div>
    </div>

    <p ng-include="'${footer}'"></p> 
</div>
</code>  

JS (code snippet 2):

app.config(['$stateProvider','$urlRouterProvider',function($stateProvider,   $urlRouterProvider) {  
    $urlRouterProvider.otherwise('/login');
    $stateProvider.state('grid', {
    url: '/grid',
    templateUrl: 'resources/html/grid.html',
    controller: 'gridCtrl'
    }).state('chDetail', {
     url: "/chDetail/:chId",
     templateUrl: "resources/html/chDetail.html",
     controller: 'chDetailCtrl'
     }).state('login', { 
     url: "/login",
     templateUrl: "resources/html/login.html",
     controller: 'loginCtrl'
     });
     }]).controller('gridCtrl', ['$scope', function($scope){
     $scope.grid =[];
     }]);

</code>

code snippet 3:-

<code>

<div ng-show="{$state.is('login')}">Item</div>
</code>

解决方案

If I've understood it correctly you want to display the login view with-out the other views like header, footer & side menu.

Then you could create an abstract state for the layout with your views header, footer, side-menu etc. and add a separate state for your login view.

The tricky part of the demo is the views definition in the abstract state:

abstract: true,
views: {
    '': {
        templateUrl: 'layout.html',
    },
    'header@root': {
        template: 'content for header'
    },
    'footer@root': {...}
}

What is the abstract state doing? The abstract state will load the layout template in the unnamed view in your main template and loads the other views that you'd like to share with the child states.

Each child state can then define the content view as needed and re-use the other views.

Please have a look at the demo below or this fiddle.

Note: The login in the demo is of course not secure and only there to show the view redirect handling. In your app you have to work with $http and with sessionStorage and tokens.

angular.module('demoApp', ['ui.router'])
	.run(function($rootScope, $state) {
            $rootScope.$on('$stateChangeError', function(evt, to, toParams, from, fromParams, error) {
          if (error.redirectTo) {
            $state.go(error.redirectTo);
          } else {
            $state.go('error', {status: error.status})
          }
        })
    })
	.factory('userService', userService)
	.config(routes);

function userService() {
	var usersMock = {
    	'testUser': {
        	username: 'testUser',
            password: '1234'
        },
        'testUser2': {
        	username: 'testUser2',
            password: '1234'
        }
    };
	var userService = {
    	user: undefined,
    	login: function(userCredentials) {
        	// later --> $http.post('auth', userCredentials).then(...)
            // for demo use local data
            var user = usersMock[userCredentials.username]
            userService.user = ( user && ( user.password == userCredentials.password ) ) ? 
            	user : undefined;
            return user;
        },
        logout: function() {
        	userService.user = undefined;
        }
    }
    
    return userService;
}
function routes($urlRouterProvider, $stateProvider) {

	$urlRouterProvider.otherwise('/');
    
    $stateProvider
    	.state('root', {
        	url: '',
        	abstract:true,
            resolve: {
            	'user': function(userService) {
                	return userService.user; // would be async in a real app
                }
            },
            views: {
            	'': {
                	templateUrl: 'layout.html',
                },
            	'header@root': {
                	template: '<h1>header View<span ng-if="user"><button ng-click="logout()">logout</button></span><span ng-if="!user"><button ng-click="login()">login</button></span></h1>',
                    controller: function($scope, $state, user, userService) {
                    	$scope.user = user;
                        $scope.login = function() {
                        	$state.go('login');
                        };
                        $scope.logout = function() {
                        	userService.logout();
                            $state.go('root.home', {}, {reload: true});
                        };
                    }
            	},
                'footer@root': {
                    template: '<p>footer view</p>'
                }
            }
        })
    	.state('root.home', {
            url: '/',
            views: {
                'content': {
                    template: 'Hello at home'
                }
            }
        })
        .state('root.about', {
            url: '/about',
            views: {
                'content': {
                    template: 'about view'
                }
            }
    	})
        .state('root.restricted', {
            url: '/restricted',
            resolve: {
            	auth: function(userService, $q, $timeout) {
                
                	var deferred = $q.defer();
                	/* //with an async
                    return UserService.load().then(function(user){
                      if (permissionService.can(user, {goTo: state})) {
                        return deferred.resolve({});
                      } else {
                        return deferred.reject({redirectTo: 'some_other_state'});
                      }
                    }*/
                    
                   $timeout(function() {
                        if ( angular.isUndefined(userService.user) ) {
                            return deferred.reject({redirectTo: 'login'});
                        }
                        else {
                            return deferred.resolve(userService.user);
                        }
                    });
                    
                    return deferred.promise;
                }
            },
            views: {
                'content': {
                    template: 'this is only visible after login. Hello {{user}}!',
                    controller: function($scope, auth) {
                    	$scope.user = auth.username;
                    }
                }
            }
    	})
        .state('login', {
            url: '/login',
            templateUrl: 'views/login.html',
            controller: function($scope, $state, userService) {
            	$scope.login = function(cred) {
                	var user = userService.login(cred);
                    
                    if (angular.isUndefined(user)) {
                    	alert('username or password incorrect.')
                    }
                    else {
                    	$state.go('root.restricted');
                    }
                };
            }
        });
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.js"></script>

<div ng-app="demoApp">
    <a ui-sref="root.home" href="#">home</a>
    <a ui-sref="root.about" href="#">about</a>
    <a ui-sref="root.restricted" href="#">restricted page</a>
    
    <div ui-view>
    </div>
    
    <script type="text/ng-template" id="views/login.html">
    	<h1>Login</h1>
        <p>Try testUser and 1234 as credentials</p>
        <label>Username</label><input ng-model="userCred.username"/>
        <label>Password</label><input type="password" ng-model="userCred.password"/>
        <button ng-click="login(userCred)">login</button>
    </script>
    
    <script type="text/ng-template" id="layout.html">
    	<div>
            <div ui-view="header"></div>
            <div ui-view="content"></div>
            <div ui-view="footer"></div>
    	</div>
    </script>
</div>

这篇关于AngularJS UI的路由器+国家需要帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆