2016-04-27 23 views
0

我有一個state需要做一些邏輯,然後它返回到模板,這花了我一段時間才弄清楚,但我終於學到了templateProvider和想出了這個;angular-ui路由器 - 從templateProvider獲取內容到html和控制器

.state('home.read', { 
    url: '/read/{id:u}', 
    templateProvider: ($stateParams:ng.ui.IStateParamsService, $http:ng.IHttpService, $settings:ISettings) => { 
     return $http({ 
      url: String.format('{0}/api/articles/read/{1}', $settings.uri(), $stateParams['id']), 
      method: 'GET', 
      withCredentials: true 
     }).then((response) => { 
      return response.data; 
     }); 
    } 
}) 

從服務器獲取我需要的數據並通過憑證等進行過濾;它確保我得到的是我需要的。

所以現在我很困惑 - 我怎麼能得到這個控制器,並得到適當的.html模板加載,所以我可以使用它?

該模板太複雜,不能作爲字符串傳遞。我真的需要它作爲一個靜態HTML文件存在。我試圖使用templateUrl,但似乎沒有工作。即使這樣做,我仍然不清楚如何將數據傳輸到控制器 - 具體而言,因爲我需要將其附加到$scope

+0

templateUrl應該工作。控制檯中是否有任何錯誤?你能上傳plunkr嗎? –

+0

'templateUrl'可以讓我進入HTML頁面,但是我仍然不清楚如何將'templateProvider'的結果轉換爲HTML頁面使用的任何控制器的'$ scope'上的有意義變量 – Ciel

+0

'templateProvider '用於動態構建動態模板。它應該返回一個字符串格式化模板(HTML的字符串表示)。 如果你想**在頁面加載之前解析**一些數據,那麼你應該看看wiki中的'resolve'選項:https://github.com/angular-ui/ui-router/wiki –

回答

0

不熟悉打字稿,所以我會在普通的js中提供解決方案。

在配置階段

.config(function($stateProvider, $urlRouterProvider){ 

$stateProvider 
    .state('read', { 
    url: '/read/:id' 
    controller: 'IndexController', 
    resolve: { 
    myResolvedData: function($stateParams, $settings, $http){ 
     return $http.get($settings.uri() + '/api/articles/read/' + $stateParams['id']); 
    } 
    } 
    }); 
}); 

IndexController

.controller('IndexController', function($scope, ... , myResolvedData){ 
//Bind resolved data to scope variable. template and controller will not load before 
//myResolvedData is resolved. 
$scope.data = { 
    fromServer: myResolvedData 
}; 
}); 
+1

是啊!這正是我需要做的。謝謝! – Ciel

+0

這就是我們在這裏:) –