加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何配置routeProvider和locationProvider在angularJS?

发布时间:2020-12-17 08:59:35 所属栏目:安全 来源:网络整理
导读:我想在angularJS中激活html5Mode,但我不知道为什么它不工作。我的代码有什么问题吗? angular .module('myApp',[]) .config(function($locationProvider,$routeProvider) { $locationProvider.html5Mode(true); $routeProvider.when('/',{ templateUrl: 'pa
我想在angularJS中激活html5Mode,但我不知道为什么它不工作。我的代码有什么问题吗?
angular
    .module('myApp',[])
    .config(function($locationProvider,$routeProvider) {
        $locationProvider.html5Mode(true);
        $routeProvider.when('/',{
           templateUrl: 'partials/home.html',controller: HomeCtrl
        });

        $routeProvider.when('/tags/:tagId',{
            templateUrl: 'partials/result.html',controller: TagResultCtrl
        });
        //$routeProvider.otherwise({redirectTo: '/home',controller: HomeCtrl});
     });

在html

<a href="tags/{{tag.id}}"><img data-ng-src="{{tag.imageUrl}}"></a>
我看到的唯一问题是相对链接和模板没有正确加载,因为这个。

from the docs regarding HTML5 mode

Relative links

Be sure to check all relative links,images,scripts etc. You must either specify the url base in the head of your main html file (<base href="/my-base">) or you must use absolute urls (starting with /) everywhere because relative urls will be resolved to absolute urls using the initial absolute url of the document,which is often different from the root of the application.

在您的情况下,您可以在配置路由时在href属性($ location.path会自动添加)以及templateUrl中添加正斜杠/。这样可以避免像example.com/tags/another这样的路由,并确保模板正确加载。

这里有一个工作原理的例子:

<div>
    <a href="/">Home</a> | 
    <a href="/another">another</a> | 
    <a href="/tags/1">tags/1</a>
</div>
<div ng-view></div>

app.config(function($locationProvider,$routeProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider
    .when('/',{
      templateUrl: '/partials/template1.html',controller: 'ctrl1'
    })
    .when('/tags/:tagId',{
      templateUrl: '/partials/template2.html',controller:  'ctrl2'
    })
    .when('/another',controller:  'ctrl1'
    })
    .otherwise({ redirectTo: '/' });
});

如果使用Chrome,您需要从服务器运行。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读