2014-09-01 30 views
0

我正在AngularJS中编写一个搜索屏幕,它在同一页面中提取和显示搜索结果。我希望网址能够反映搜索中使用的参数。我已经这么远(简体):AngularJS:用相同的搜索URL重新加载视图

<input type="text" ng-model="search.name"> 
<button ng-click="search()">Search</button> 

<ul> 
    <li ng-repeat="widget in widgets">...</li> 
</ul> 

与控制器(启动CoffeeScript的):

module.controller "WidgetController", ($scope, $http, $routeParams, $location) -> 
    if $routeParams.name 
    $scope.search.name = $routeParams.name 
    config = 
     params: 
     name: $routeParams.name 
    $http.get("/api/widgets", config).success (data) -> 
     $scope.widgets = data 

    $scope.search = -> 
    $location.path("widgets").search(name: $scope.search.name) 

这工作得很好 - 当我点击 “搜索”,URL被更新,以反映查询,并返回结果。

唯一的问题是,如果我做了一个搜索,然后再次用相同的查询单击搜索按钮,结果不刷新。据推测,$location服务发现当前URL已经与请求的URL相同,并且不会重新加载视图。有没有一种好方法让它在这种情况下进行刷新?

回答

1

我觉得这里的问题是,你依赖于控制器清爽,我会做的是把该位作为一种方法

doSearch = -> 
    if $routeParams.name 
    $scope.search.name = $routeParams.name 
    config = 
     params: 
     name: $routeParams.name 
    $http.get("/api/widgets", config).success (data) -> 
     $scope.widgets = data 

那么你可以可以运行搜索方法搜索

$scope.search = -> 
    $location.path("widgets").search(name: $scope.search.name) 
    doSearch() 

并防止控制器重新加载,您可以在路线上设置正确的值

+0

不错的建议,谢谢。我最终使用了'$ location.search(name:$ scope.search.name)',并在'$ routeProvider'中设置了'reloadOnSearch:false'。我试过的另一种方法是在更新位置后运行'$ route.reload()',但我更喜欢你的方法,因为它不需要重新加载视图。 – 2014-09-01 11:25:20

相关问题