如何配置routeProvider和locationProvider在angularJS?

前端之家收集整理的这篇文章主要介绍了如何配置routeProvider和locationProvider在angularJS?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在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,您需要从服务器运行。

原文链接:https://www.f2er.com/angularjs/146472.html

猜你在找的Angularjs相关文章