External Links in Angular App

若如初见. 提交于 2019-12-07 18:06:23

问题


I'm in the process of incorporating Angular into a single page of an existing rails app.

Everything is working perfectly with the routing within the page using the following

app.config(function($routeProvider, $locationProvider) {
    $routeProvider
      .when('/services/:id', {
        templateUrl: "/javascripts/angular/templates/service_ui/service.html",
        controller: "ServiceCtrl"
     })

     $locationProvider.html5Mode(true);
});

However, I'd like to maintain normal functionality for links that are not related to Angular. For example, we have a number of links in the header that link elsewhere that are now being caught by the angular router.

I've found some potential solutions at: https://groups.google.com/forum/?fromgroups#!topic/angular/basidvjscRk

But the base path method doesnt seem to work..and the target="_self" method is rather obtrusive. Is there a better way to let angular ignore routes that aren't specified in the config function?

I know there is an .otherwise() method but again this seems like a hack. Am I missing something?

Thanks so much!


回答1:


We have a relatively "traditional" web application in that most of the links trigger full page reloads; very few links go through Angular's routing system. Right after our module definition, we have the following:

app.run(function($location, $rootElement) {
  $rootElement.off('click');
});

This stops the built-in interception of clicks that Angular uses to manipulate the URL and such when you click on a link; the catch is that you now have to use $location manually whenever you want Angular to do its URL magic (e.g. via an ngClick and a function that manipulates $location accordingly).

You may consider using $rootElement.off combined with a special directive or configuration function that re-installs this behavior on links that you detect contain a certain URL fragment.




回答2:


Another option that may work for you is to change the $rootElement: the link interception only occurs within the element that is declared as the ng-app.

In my case, I switched from <body ng-app="myApp"> to <section id="my-rich-area" ng-app="myApp">.

This worked for me as I didn't have any same-domain, non-angular links within that section, ymmv.



来源:https://stackoverflow.com/questions/16755240/external-links-in-angular-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!