2016-04-15 32 views
1

我使用$http作爲ajax調用的角度,使用ui.router作爲routing使用ui.route時根據url更改請求url

路線

.state("/dashboard.inactive", { 
    url: "/inactive", 
    templateUrl: "angular/templates/dashboard/inactive.html", 
    controller: "dashboardCtrl" 
}) 
.state("/dashboard.drafts", { 
    url: "/drafts", 
    templateUrl: "angular/templates/dashboard/drafts.html", 
    controller: "dashboardCtrl" 
}); 

所以下面的代碼工作,如果它是一個單一的URL。

控制器

app.controller('dashboardCtrl', function ($scope, DashboardFactory){ 
    DashboardFactory.listings(function(DashboardFactory) { 
     $scope.results = DashboardFactory; 
    }); 
}); 

下面的工廠從drafts.json資源只有獲取。所以當URL變爲非活動狀態時,我希望它分別從inactive.jsonactive.json中獲取。

app.factory('DashboardFactory', function($http){ 
    return { 
     listings: function(callback){ 
      $http.get('drafts.json').success(callback); 
     } 
    }; 

}); 

總之我需要發送基於所述URL

1) '/drafts.json' 
2) '/inactive.json' 
3) '/active.json' 

我可以爲每個活動創建不同的控制器請求到低於3的網址中的任何一個,不活躍和草稿,並使其按預期方式獲取。但有沒有更好的方法來做到這一點?

回答

2

你可以使用UI航線的$state服務,以告訴在哪個國家。 只需注入$狀態給您的服務,然後才能訪問當前狀態的配置使用$state.current

app.factory('DashboardFactory', 
    function($http, $state){ 
     return { 
      listings: function(callback){ 
       var currentView = $state.current.url.replace('/', ''); 
       $http.get(currentView + '.json').success(callback); 
      } 
     }; 
    }); 

一個更好的解決辦法是要麼使用state配置的params財產或添加一些自定義屬性,如:

.state("/dashboard.inactive", { 
    url: "/inactive", 
    templateUrl: "angular/templates/dashboard/inactive.html", 
    controller: "dashboardCtrl", 
    params: { 
    json: 'inactive.json' 
    } 
}) 
.state("/dashboard.drafts", { 
    url: "/drafts", 
    templateUrl: "angular/templates/dashboard/drafts.html", 
    controller: "dashboardCtrl", 
    params: { 
    json: 'drafts.json' 
    } 
}); 

它在documentation描述。

+0

謝謝。第一個解決方案有效。但我認爲第二個更優雅。但是我怎樣才能在工廠中參考這些參數?此外文檔鏈接不起作用 – Abhilash

+1

我已修復鏈接到文檔。你如我所示注入$ state,並且可以引用配置對象,你可以在其中添加params屬性(或任何其他屬性),然後通過'$ state.current'獲得它。 – yccteam

+0

謝謝合作... – Abhilash