-1
ui-router
中的子狀態組件在讀取其父數據時遇到問題。記錄$stateParams
時,它顯示正確的信息。該數據作爲參數傳遞給ui-sref
屬性,這會導致向用戶顯示正確的信息,但不是。ui路由器子狀態無法訪問父狀態數據
這是正在記錄的項目標識(取決於哪個項目被點擊)。
爲什麼孩子狀態patents.patent
無法讀取父狀態patents
的數據?
var app = angular.module('myApp', ['ui.router']);
app.config(['$stateProvider', function($stateProvider) {
var states = [
{
name: 'patents',
url: '/patents',
component: 'patents',
resolve: {
patents: function(patentsService) {
return patentsService.fetchAllPatents();
}
}
},
{
name: 'patents.patent',
url: '/{patentId}',
component: 'patent',
resolve: {
patent: function(patents, $stateParams) {
return patents.find(function(patent){
return patent.id === $stateParams.patentId;
})
}
}
}
]
states.forEach(function(state) {
$stateProvider.state(state);
});
}]);
app.service('patentsService', function($http) {
var service = {
fetchAllPatents: function() {
return $http.get('http://localhost:8080/Sprint002b/restpatent/', {cache: true}).then(function(resp){
return resp.data
});
}
};
return service;
});
部件
angular.module('myApp').component('patents', {
bindings: { patents: '<' },
template: ' <div>' +
'<div>' +
'<table>' +
'<thead>' +
'<tr>' +
'<td>Application No. </td>' +
'<td>Client Ref</td>' +
'<td>Cost now</td>' +
'<td>Cost band end</td>' +
'<td>Cost next</td>' +
'<td>Renewal Date</td>' +
'</tr>' +
'</thead>' +
'<tbody>' +
'<tr ng-repeat="patent in $ctrl.patents">' +
'<td><a ui-sref="patents.patent({patentId: patent.id})" ng-bind="patent.applicationNumber"></a></td>' +
'<td ng-bind="patent.clientRef"></td>' +
'<td ng-bind="patent.currentRenewalCost">$</td>' +
'<td ng-bind="patent.costBandEndDate"></td>' +
'<td ng-bind="patent.renewalCostNextStage"></td>' +
'<td ng-bind="patent.renewalDueDate"></td>' +
'</tr>' +
'</tbody>' +
'</table>' +
'<div ui-view></div>' +
'</div>' +
'</div>'
});
angular.module('myApp').component('patent', {
bindings: { patent: '<' },
template: '<h3>A patent!</h3>' +
'<div><p>Name: {{$ctrl.patent.id}}</p></div>' +
'<div><p>Id: {{$ctrl.patent.applicationNumber}}</p></div>' +
'<div><p>Company: {{$ctrl.patent.clientRef}}</p></div>' +
'<button ui-sref="people">Close</button>'
});
UPDATE
我設法用數據填充子狀態,但只填充JSON對象中的第一項。
我更改了我的配置文件中的resolve
屬性中返回的數據。數據正在加載,但在選擇項目時不會更改。
關於我該怎麼做的任何想法?這是在plunkr https://plnkr.co/edit/jbZgIg?p=preview
{
name: 'patents.patent',
url: '/{patentId}',
component: 'patent',
resolve: {
patent: function(patents, $stateParams) {
return patents.find(function(patent){
return $stateParams; // changed from patent.id === $stateParams.patentId
})
}
}
}
這可能是一個問題,'patentId'是'string','patent.id'是'number'。如果是這樣,你可以將你的url改爲'/ {patentId:int}',它將把參數解析爲'$ stateParams'內的一個整數 –