2014-09-01 29 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

相關問題