简体   繁体   中英

How can I tell, inside a controller, if it has been run from ng-controller or a route

I have an AngularJS controller which is used both on a specific page, defined in a route:

when("/search/:term", {controller:'SearchCtrl',  templateUrl:'/static/templates/supersearch/list.html'});

and also attached to an element in the header, which is used on all pages:

<div ng-controller="SearchCtrl">
  <form class="navbar-form pull-left super-search">
    ...
  </form>
<div>

How can I tell, from within the controller, which context it is being run in?

Things I've tried:

ng-init

I tried using <div ng-controller="SearchCtrl" ng-init="init(true)"> to tell the controller if it was running from the header search form, but it seems that ng-init is executed after the controller, so it doesn't have access to the passed parameter.

Passing $element

If I inject $element to the controller, I am able to access the DOM node that the ng-controller directive is attached to, however angular raises an error in the case of the page with the route, because there is no $element available to inject.

So I either need some way to pass a parameter to the controller, or some way to tell which context the controller is being run from (inline ng-controller vs. route). Thanks!

我建议使用注入到控制器功能中的$routeParams 服务来区分情况。

The actual processing of the search must be done in the service layer. Not in the controller. Also merging basically two controllers into one can lead to a whole host of problems.

Consider having two controllers. One for the full seach and one for the header search. Both these controllers get the Search service injected which will handle the search.

app.controller('HeaderSeachController', function (Search) {
    Search.headerSearch();
});

app.controller('SeachController', function (Search) {
    Search.search();
});

app.service('Search', function () {
    return {
        headerSearch: function () { ... },
        search: function () { ... },
        _sharedLogic: function () { ... }
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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