2014-12-07 21 views
4

我需要一個路由參數傳遞給服務器使用模板響應,所以我試圖用一個templateProvider每幾篇文章/其他堆棧溢出文檔。角UI路由器templateProvider從來沒有所謂

我沒有得到任何的JavaScript錯誤,但從來沒有執行以下templateProvider方法。當templateUrl屬性未被註釋掉時,此路線正常工作。

$stateProvider 
.state('org.contacts.add', { 
    url: '/add', 
    views: { 
    '[email protected]': { 
     // templateUrl: '/templates/issues/add', 
     controller: 'ContactsAddController', 
     templateProvider: function($route, $templateCache, $http) { 
      var url = '/templates/' + $route.current.params.org + '/contacts/add'; 
      $http.get(url, {cache: $templateCache}).then(function(html){ 
       return html; 
      }); 
     }] 
    } 
    } 
}) 

一些實驗後,似乎$route是造成麻煩。拿出來並使用$stateParams至少會激發這個代碼/控制器。

然而,當我看到Ajax調用射擊和正確的HTML的響應,它從來沒有加載到視圖。

templateProvider: function ($stateParams, $http, $templateCache) { 
     var url = '/templates/contacts/add'; 
     $http.get(url, {cache: $templateCache}).then(function(html){ 
      return html; 
     }); 
    } 

回答

4

我猜你需要返回一個$promise這個工作。檢查出的UI-Router wiki使用的示例:

$stateProvider.state('contacts', { 
    templateProvider: function ($timeout, $stateParams) { 
    return $timeout(function() { 
     return '<h1>' + $stateParams.contactId + '</h1>' 
    }, 100); 
    } 
}) 

注意與return $timeout(...開頭的行。您是否嘗試過返回創建的$http.get()

+0

這讓我認識到,通過取出'$ route',並使用'$ stateParams',我至少得到應用路線和控制器加載。我現在看到幾乎所有的東西都能正常工作 - http請求被創建,參數是正確的,但HTML響應從未被加載到我的視圖中。我將用新代碼更新我的問題 – helion3 2014-12-07 18:55:58

+0

直接返回http承諾只是將'[object object]'注入到視圖中。 – helion3 2014-12-07 19:00:07

+1

耶,解決了它。看看角度ui路由器本身的來源,這是他們用的:return $ http.get(url,{cache:$ templateCache})。then(function(response){return response.data;});' – helion3 2014-12-07 19:17:28