简体   繁体   English

在某些浏览器上将服务注入Controller

[英]Inject Services to Controller on certain browsers

I have a controller which uses the $location service in angular, however we only need to use it in HTML5 mode, if the browser doesn't support history.pushstate we want to omit the service from the controller so it doesn't rewrite the URL to /#/2016-17 and instead doesn't do any routing. 我有一个控制器,它在angular中使用$location服务,但是如果浏览器不支持history.pushstate ,我们只需要在HTML5模式下使用它history.pushstate我们想从控制器中省略该服务,以便它不重写指向/#/2016-17 URL,而不执行任何路由。 However if you inject $location into a controller, it automatically routes using the hashbang method. 但是,如果将$location注入控制器,它将使用hashbang方法自动路由。

Code below for reference: 以下代码供参考:

function SearchAdvancedController($location) {
    $location.url("/", false);
}

function config($locationProvider) {
    $locationProvider.html5Mode({
     enabled: true,
     rewriteLinks: false,
     requireBase: false
    });
}

Any ideas? 有任何想法吗?

Thanks guys. 多谢你们。

You should always be injecting the service into your controller, unless you want a lot of if..else conditions which check whether the service exists or not. 除非您需要很多if..else条件来检查服务是否存在,否则您应该始终将服务注入到控制器中。 The simple thing to do is to define your own service to change URLs, and conditionally have it do nothing: 简单的事情是定义您自己的服务来更改URL,并有条件地使其不执行任何操作:

module.service('MyLocation', function ($location) {
    this.url = function () {
        if (/* browser supports pushstate */) {
            $location.url.apply($location, arguments);
        }
    };
});

function SearchAdvancedController(MyLocation) {
    MyLocation.url('/', false);
}

You may want to play around with decorators for this purpose too. 您可能也为此目的而与装饰器一起玩耍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM