当 reloadOnSearch 为 false 时,$location.search 上的 AngularJs $watch 不起作用 [英] AngularJs $watch on $location.search doesn't work when reloadOnSearch is false
问题描述
我的 routeProvider 路由的 reloadOnSearch 设置为 false :
My routeProvider for route has reloadOnSearch set to false :
$routeProvider
.when(
"/film/list",
{
templateUrl: '/film/list.html',
controller: FilmListController,
reloadOnSearch: false
}
....
)
我这样做是因为我不希望在查询字符串更改后重新加载整个控制器,但我仍然使用它并且网址如下所示:film/list?sort=isbn&order=asc&偏移=0
.现在,每当查询字符串更改时,我都想从我的控制器调用一个函数.所以我尝试在控制器中设置一个 $watch:
I did this because I don't want the whole controller to be reloaded after query string changes, but I still use it and the url looks like this: film/list?sort=isbn&order=asc&offset=0
. Now whenever query string changes I want to call a function from my controller. So I tried to set up a $watch in the controller:
$scope.location = $location;
$scope.$watch( 'location.search()', function( search) {
$scope.list();
});
但这行不通.如果我将 $watch 设置为监视查询字符串的单个参数的更改,则它可以工作.但我不想为查询字符串的每个参数设置 $watch .我现在使用的解决方案是这样的:
But this doesn't work. If I set $watch to watch changes of an individual parameter of a query string, then it works. But I don't want to set $watch for every parameter of my query string. The solution I use now is this:
$scope.location = $location;
$scope.$watch( 'location.url()', function( url ) {
if($location.path() == '/film/list')
$scope.list();
});
因此,我不是观察搜索,而是观察整个 url,然后检查路径是否是我在 routeProvider 中设置的路径,以便有条件地调用该函数.我不喜欢这个解决方案的是我必须明确输入要匹配的 $location.path 的值.
So instead of watching for the search, I watch the whole url, and then I check if the path is the one I set in routeProvider to conditionally call the function. What I don't like about this solution is that I have to explicilty type the value for $location.path to be matched.
谁能提出更好的解决方案,也许可以解释一下为什么 $watch 对 $location.search() 不起作用?
Can anyone suggest a better solution, and perhaps explain me why is $watch not working for $location.search() ?
推荐答案
您可以在控制器中监听 $routeUpdate
事件:
You can listen for $routeUpdate
event in your controller:
$scope.$on('$routeUpdate', function(){
$scope.sort = $location.search().sort;
$scope.order = $location.search().order;
$scope.offset = $location.search().offset;
});
这篇关于当 reloadOnSearch 为 false 时,$location.search 上的 AngularJs $watch 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!