在路由中运行 .run 时,从 Angularjs 中的 url 中删除 # [英] Removing # from url in Angularjs while having .run in routes

查看:21
本文介绍了在路由中运行 .run 时,从 Angularjs 中的 url 中删除 #的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在 AngularJS 中的 app.js 路由文件

var app = angular.module('myApp', ['ngRoute', 'ngAnimate', 'toaster']);app.config(['$routeProvider',功能($routeProvider){$routeProvider.当('/登录',{title: '登录',templateUrl: 'resources/views/layouts/loginUser.php',控制器:'authCtrl'}).什么时候('/', {title: '登录',templateUrl: 'resources/views/layout/login.php',控制器:'logoutCtrl'}).when('/重置', {title: '重置密码',templateUrl: 'resources/views/layouts/forgetPassword.php',控制器:'authCtrl'}).when('/无效令牌', {title: '登录',templateUrl: 'resources/views/layout/invalidtoken.php',控制器:'authCtrl',角色:'0'})//$locationProvider.html5Mode(true);}]).run(function ($rootScope, $location, Data, $http) {$rootScope.$on("$routeChangeStart", function (event, next, current) {var nextUrl = next.$$route.originalPath;if (nextUrl == '/signin' || nextUrl == '/login' || nextUrl == '/verify' || nextUrl == '/register' || nextUrl == '/registered' || nextUrl =='/reset' || nextUrl == '/resetdone' || nextUrl == '/registersuccess'){$location.path(nextUrl);}别的{$location.path('/');}});});

这里我使用 .run 来处理一些请求.

我想从 url 中删除 # 以使 url 漂亮,

所以我确实按照建议删除了#这里

app.config(['$routeProvider', '$locationProvider'功能($routeProvider,$locationProvider){

最后一行

$locationProvider.html5Mode(true);

但是应用程序没有发生任何事情,它的 url 中仍然有 #.

即使我尝试了这种方式

我怎样才能做到这一点?

更新:

如果我这样做

.run(function ($rootScope, $location, Data, $http, $locationProvider) {

最后一行

$locationProvider.html5Mode(true);

我收到此错误

错误:$injector:unpr未知提供者

我尝试了很多方法,但都没有奏效.

更新 2:

或者任何人都可以建议一个 angularjs 示例的链接,它提供了在 url 中没有 # 的示例?

解决方案

为什么要使用 .run() ?将 <base href="/"/> 添加到您 <head> 或正文的开头(第一行),然后匹配您的 .run() 试试这个( .otherwise("/path") 到你的 $routeProvider):

var app = angular.module('myApp', ['ngRoute', 'ngAnimate', 'toaster']);app.config(['$routeProvider', '$locationProvider',功能($routeProvider,$locationProvider){$routeProvider.当('/登录',{title: '登录',templateUrl: 'resources/views/layouts/loginUser.php',控制器:'authCtrl'}).什么时候('/', {title: '登录',templateUrl: 'resources/views/layout/login.php',控制器:'logoutCtrl'}).when('/重置', {title: '重置密码',templateUrl: 'resources/views/layouts/forgetPassword.php',控制器:'authCtrl'}).when('/无效令牌', {title: '登录',templateUrl: 'resources/views/layout/invalidtoken.php',控制器:'authCtrl',角色:'0'}).除此以外("/");$locationProvider.html5Mode(true);}]);

如果您仍然遇到问题,我建议您使用 https://github.com/angular-ui/用户界面路由器

更新:

你的index.html

<html lang="en" ng-app="myApp"><头><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>绿色跳跃</title><link rel="shotcut icon" type="favicon.ico" href="public/images/favicon.ico"/><link rel="icon" type="favicon.ico" href="public/images/favicon.ico"/><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script><script src="https://code.angularjs.org/1.4.2/angular-route.min.js"></script><body ng-cloak=""><base href="/"><div data-ng-view="" id="ng-view" class="slide-animation"></div><脚本>var app = angular.module('myApp', ['ngRoute']);app.config(['$routeProvider', '$locationProvider',功能($routeProvider,$locationProvider){$routeProvider.什么时候('/', {title: '家',templateUrl: 'home.html',控制器:'homeCtrl'}).when('/登录', {title: '登录',templateUrl: 'login.html',控制器:'authCtrl'}).when('/退出', {title: '退出',templateUrl: 'logout.html',控制器:'logoutCtrl'}).when('/仪表板', {title: '仪表板',templateUrl: 'dashboard.html',控制器:'dashboardCtrl'}).除此以外('/');$locationProvider.html5Mode(true);}]).run(function ($rootScope, $location, $http, loginSrv) {$rootScope.$on("$routeChangeStart", function (event, next, current) {var nextUrl = next.$$route.originalPath;var orUseUrl = $location.path();控制台日志(nextUrl);if (nextUrl === '/logout'){loginSrv.logout();}if (nextUrl === '/login'){loginSrv.login();}if (loginSrv.loggedin === false) { $location.path('/');}else { $location.path(nextUrl);}});});app.service("loginSrv",function(){var ls = 这个;ls.loggedin = 假;ls.logout = 函数(){ls.loggedin = 假;}ls.login = 函数(){ls.loggedin = 真;}});app.controller("homeCtrl",function($scope, loginSrv){$scope.loggedin = loginSrv.loggedin;})app.controller("dashboardCtrl",function($scope, loginSrv){$scope.loggedin = loginSrv.loggedin;})app.controller("authCtrl",function($scope, loginSrv){$scope.loggedin = loginSrv.loggedin;})app.controller("logoutCtrl",function($scope, loginSrv){$scope.loggedin = loginSrv.loggedin;})</html>

所有其他模板都与此相同.为 home.htmllogin.htmldashboard.htmllogout.html 复制粘贴以下内容.Plunker 将无法显示客户端路由的问题.尝试这个.这是完全功能性的代码.

<div><a href="/">首页</a>|<a href="/login">登录</a>|<a href="/dashboard">仪表板</a>|<a href="/logout">注销</a></div><div>这是来自 home/login/dashboard/logout 控制器.登录:{{loggedin}}</div>

Here is my app.js route file in AngularJS

var app = angular.module('myApp', ['ngRoute', 'ngAnimate', 'toaster']);
app.config(['$routeProvider',
    function ($routeProvider) {
        $routeProvider.
                when('/login', {
                    title: 'Login',
                    templateUrl: 'resources/views/layouts/loginUser.php',
                    controller: 'authCtrl'
                })
                .when('/', {
                    title: 'Login',
                    templateUrl: 'resources/views/layout/login.php',
                    controller: 'logoutCtrl'
                })
                .when('/reset', {
                    title: 'Reset Password',
                    templateUrl: 'resources/views/layouts/forgetPassword.php',
                    controller: 'authCtrl'
                })
                .when('/invalidtoken', {
                    title: 'Login',
                    templateUrl: 'resources/views/layout/invalidtoken.php',
                    controller: 'authCtrl',
                    role: '0'
                })

                //$locationProvider.html5Mode(true);
    }])


        .run(function ($rootScope, $location, Data, $http) {
            $rootScope.$on("$routeChangeStart", function (event, next, current) {
                     var nextUrl = next.$$route.originalPath;

                    if (nextUrl == '/signin' || nextUrl == '/login' || nextUrl == '/verify' || nextUrl == '/register' || nextUrl == '/registered' || nextUrl == '/reset' || nextUrl == '/resetdone' || nextUrl == '/registersuccess')
                    {
                        $location.path(nextUrl);
                    }
                     else
                    {   

                        $location.path('/');
                    }      
            });
        });

Here i use .run to handle few requests.

I want to remove the # from the url to make the url pretty,

So i did like this to remove the # as suggested here

app.config(['$routeProvider', '$locationProvider'
    function ($routeProvider, $locationProvider) {

and in the last line

$locationProvider.html5Mode(true);

But nothing is happening to the application, it stills haves # in the url.

Even i tried this way

How can i achieve this ?

Update :

If i do

.run(function ($rootScope, $location, Data, $http, $locationProvider) {

and in the last line

$locationProvider.html5Mode(true);

I am getting this error

Error: $injector:unpr
Unknown Provider

I have tried in many ways, but none of them working.

Update 2 :

Or can anyone suggest a link of angularjs example which provides example without # in url ?

解决方案

Why do you want to use the .run() ? Add <base href="/" /> to you <head> or start of your body (first line) and then to match the logic of your .run() try this ( .otherwise("/path") to your $routeProvider):

var app = angular.module('myApp', ['ngRoute', 'ngAnimate', 'toaster']);
app.config(['$routeProvider', '$locationProvider',
    function ($routeProvider, $locationProvider) {
        $routeProvider.
                when('/login', {
                    title: 'Login',
                    templateUrl: 'resources/views/layouts/loginUser.php',
                    controller: 'authCtrl'
                })
                .when('/', {
                    title: 'Login',
                    templateUrl: 'resources/views/layout/login.php',
                    controller: 'logoutCtrl'
                })
                .when('/reset', {
                    title: 'Reset Password',
                    templateUrl: 'resources/views/layouts/forgetPassword.php',
                    controller: 'authCtrl'
                })
                .when('/invalidtoken', {
                    title: 'Login',
                    templateUrl: 'resources/views/layout/invalidtoken.php',
                    controller: 'authCtrl',
                    role: '0'
                })
. otherwise("/");
           $locationProvider.html5Mode(true);
    }]);

If you still face issues, I recommend https://github.com/angular-ui/ui-router

Update:

your index.html

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <title>Green Hopping</title>
        <link rel="shotcut icon" type="favicon.ico" href="public/images/favicon.ico" />
        <link rel="icon" type="favicon.ico" href="public/images/favicon.ico" />
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
        <script src="https://code.angularjs.org/1.4.2/angular-route.min.js"></script>

    </head>
    <body ng-cloak="">
      <base href="/">
        <div data-ng-view="" id="ng-view" class="slide-animation"></div>
    </body>

    <script>
      var app = angular.module('myApp', ['ngRoute']);
        app.config(['$routeProvider', '$locationProvider',
            function ($routeProvider, $locationProvider) {
                $routeProvider.
                        when('/', {
                            title: 'Home',
                            templateUrl: 'home.html',
                            controller: 'homeCtrl'
                        })
                        .when('/login', {
                            title: 'Login',
                            templateUrl: 'login.html',
                            controller: 'authCtrl'
                        })
                        .when('/logout', {
                            title: 'Logout',
                            templateUrl: 'logout.html',
                            controller: 'logoutCtrl'
                        })
                        .when('/dashboard', {
                            title: 'Dashboard',
                            templateUrl: 'dashboard.html',
                            controller: 'dashboardCtrl'
                        })          
                        .otherwise('/');              
                        $locationProvider.html5Mode(true);
            }])
        .run(function ($rootScope, $location, $http, loginSrv) {
            $rootScope.$on("$routeChangeStart", function (event, next, current) {
                    var nextUrl = next.$$route.originalPath;
                    var orUseUrl = $location.path();
                    console.log(nextUrl);
                    if (nextUrl === '/logout'){loginSrv.logout();}
                    if (nextUrl === '/login'){loginSrv.login();}
                    if (loginSrv.loggedin === false) { $location.path('/'); } 
                    else { $location.path(nextUrl); }
            });
        });
        app.service("loginSrv",function(){
          var ls= this;
          ls.loggedin = false;
          ls.logout = function(){
            ls.loggedin = false;
          }
          ls.login = function(){
            ls.loggedin = true;
          }
        });
        app.controller("homeCtrl",function($scope, loginSrv){
          $scope.loggedin = loginSrv.loggedin;
        })     
        app.controller("dashboardCtrl",function($scope, loginSrv){
          $scope.loggedin = loginSrv.loggedin;
        })                    
        app.controller("authCtrl",function($scope, loginSrv){
          $scope.loggedin = loginSrv.loggedin;
        })
        app.controller("logoutCtrl",function($scope, loginSrv){
          $scope.loggedin = loginSrv.loggedin;
        })        
    </script>

</html>

All other templates are same like this. Copy paste the following for home.html , login.html , dashboard.html , logout.html . Plunker will not be able to show issues with routes for client side. Try this. This is completely functional code.

<div>
    <div><a href="/">Home</a> | 
    <a href="/login">Login</a> | 
    <a href="/dashboard">Dashboard</a> | 
    <a href="/logout">Logout</a></div>

    <div> This is from the home/login/dashboard/logout Controller. Loggedin: {{loggedin}}</div>
</div>

这篇关于在路由中运行 .run 时,从 Angularjs 中的 url 中删除 #的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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