"Angularjs" "learning experience" routing combat

Source: Internet
Author: User

Today, let's take a look at the routing module in angular. In our actual project, the switching of each page is often related to auth. For example, the background of my site, is required to login to the user to go in, then we use ANGULARJS to do the front-end routing should be how to complete this function?

------------------------------------------------------------------------

Let's start by imagining the simplest scenario. Our application has two pages, login page after the content page, the request is to verify that the login is successful before entering the content page, let us together to implement this example. Of course I think my method may be relatively low, but in the learning phase we can first make the function more important than anything else.

First, use bootstrap to write a simple login page. Specific bootstrap code I will not say, we are concerned about how angular in the face of the use up

<divclass="col-md-offset-3 col-md-4">    <formclass="form"role="form"name="loginForm"ng-submit="loginCheck()">        <div class="form-group">            <labelclass="control-label">用户名</label>            <input type="text"class="form-control"required placeholder="请输入管理员账号"ng-model="admin.username">        </div>        <divclass="form-group">            <labelclass="control-label">密码</label>            <inputtype="password"class="form-control"ng-model="admin.pwd"required placeholder="请输入密码">        </div>        <divng-show="showError"class="alert alert-danger alert-dismissible" role="alert">              <buttonng-click="showError=false"type="button"class="close" data-dismiss="alert"><spanaria-hidden="true">&times;</span><spanclass="sr-only">关闭</span></button>              用户名或密码错误!!你还有一次机会        </div>        <inputtype="submit"class="btn btn-primary btn-lg"value="登录"ng-disabled="loginForm.$invalid">    </form>       </div>

The effect is as follows

Of course, I have some CSS layout, sticky code may have been wrong in the past Oh, at least in the outermost plus a div class= "row"

You can also see, I added a ng-disabled to the login button, when the form does not pass the verification is not a point to login.

Then I added a hint of tips, using the Ng-show, in the controller will have a ShowError property to control its display, when verifying the account password error ShowError to True.

When we verify the error

Then let's take a look at the routing

varmyApp = angular.module(‘myApp‘, [‘ui.router‘,‘myModule‘]);myApp.run(function($rootScope, $state, $stateParams){    $rootScope.$state = $state;    $rootScope.$stateParams = $stateParams;    $rootScope.$state.isLogin = false;});myApp.config(function($stateProvider, $urlRouterProvider) {    $urlRouterProvider.otherwise(‘/login‘);    $stateProvider        .state(‘login‘,{            url        : ‘/login‘,            templateUrl : ‘tpls/login.html‘,            controller  : ‘LoginController‘        })        .state(‘index‘,{            url        : ‘/index‘,            templateUrl : ‘tpls/index.html‘,            controllerProvider : function($rootScope){                if($rootScope.$state.isLogin == false){                    $rootScope.$state.go(‘login‘);                }                returnfunction(){};            }        });    }

Because in the entire page we will use the login status, so I bind the login status to Rootscope, IsLogin just start is false indicates not logged in.

Then look at the route inside, login this is very simple, mainly look at the index page.

The key step is the controller of the index, where I choose to generate the controller in a Controllerprovider way, and see that we finally actually return an empty function, But before returning to the empty Controller (index page has not resolved), I can do something, that is to verify the permissions!

If $rootscope. $state. IsLogin is false and is not logged in, jump directly to the login page. Jump using the Go method inside the $state, the variable in Go is the state name of each of our pages, that is, the first parameter of states. I am go (' login '), it jumps to the state of the first parameter is the login page, that is, the login page. In other words, if the verification is unsuccessful after login, we will skip to the login page when we enter/index in the Address bar.

Then take a look at our validation module.

myModule   .controller(‘LoginController‘function($scope,$rootScope,$http){      $scope.showError = false;      $scope.loginCheck = function(){        varusername = $scope.admin.username;    varpwd = $scope.admin.pwd;    var loginSuccess = false;    http.get(‘/acm-admin/data/user.json‘)     .success(function(response){       for(vari=0; i<response.length; i++){         if(response[i].username == username && response[i].pwd == pwd){        $rootScope.$state.isLogin = true;        loginSuccess = true;        $rootScope.$state.go(‘index‘);         }       }       if(!loginSuccess){        $scope.showError = true;       }    });   }  })

Initialize we give ShowError a value of false, do not display the error prompt box. Then take a look at verifying this method of login. First gets the user name and password entered by the user, setting the status of the logon success to False. Then through the $http.get, to the designated place to fetch a JSON file, it is clear that this is a false data, we put the default user name and password into this JSON file. After removing the preset user name and password, and the user input to compare, I believe this is very simple, you can certainly see clearly. If the user name and password are both on, set the login status to True, and the logon success is set to true. Then use the $state go method to jump to the index page.

If the login information verification fails, then the ShowError is assigned to true, the page will display a message.

----------------------------------------------------------------------------

How about, it's easy. Of course there are other ways to implement this function, and my above methods are likely to have a lot of security risks, and the division of the module is not clear, indifferent actual deployment is not recommended so write. We can optimize the improvement of a lot of places, such as the validation of the module should be independent out, or users have any way to easily bypass this login protection? This is left to the small partners themselves to explore ... Continue to study angular, everyone good night!!

"Angularjs" "learning experience" routing combat

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.