[英]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: 我有一个AngularJS控制器,它在路由中定义的特定页面上都使用:
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 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. 我尝试使用
<div ng-controller="SearchCtrl" ng-init="init(true)">
告诉控制器它是否从标头搜索表单中运行,但是似乎ng-init
是在控制器之后执行的,因此它无权访问传递的参数。
Passing $element 传递$ 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. 如果我将
$element
注入控制器,则可以访问ng-controller
指令附加到的DOM节点,但是在带有路由的页面的情况下angular会引发错误,因为没有$element
可用于注入。
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). 所以我要么需要某种方法来将参数传递给控制器,要么需要某种方法来告诉控制器正在从哪个上下文运行(内联
ng-controller
与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. 这两个控制器都注入了将处理搜索的
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 () { ... }
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.