[英]Back/Return button with AngularJS
我是Angular的新手,有問題。
我的頁面上有一個項目列表(一些約會)。
約會Summary.chtml
<div class="border-section">
<table>
<thead>
...
</thead>
<tbody>
<tr ng-repeat="app in appts">
<td>
<a href="#/Appointments/AppointmentsSummary/MessageHistory/{{app.patientId}}">
<button type="button">Message history</button>
</a>
</td>
</tr>
</tbody>
</table>
</div>
我有一個用於此模板的控制器:
function AppointmentsSummaryController($scope, $location, AppointmentResource) {
console.log("loaded..");
$scope.appts = AppointmentResource.getAll({
.....(params)
});
}
當我單擊AppointmentsSummary.html上的“消息歷史記錄”按鈕時-我重新定位到MessageHistiry.html頁面,該頁面具有“后退”按鈕。
<a href="#/Appointments/AppointmentsSummary">
<button type="button">Back</button>
</a>
當我按下此按鈕時,我返回到約會列表並重新加載了AppointmentsControllerSummary,並且$ scope.appts變為null。
對於頁面之間的路由,我使用$ routeProvider(與下面相同)
$routeProvider.when(/Appointments/AppointmentsSummary/MessageHistory/:patientId', {
controller:'MessageHistoryController',
templateUrl:'Template/MessageHistory',
reloadOnSearch: false
我可以不重新加載該控制器並保存$ scope數據嗎?
您需要將數據保存在服務中。 服務是單例,這意味着它們始終返回相同的實例,因此保留狀態。 控制器在每次加載時都會重新實例化,因此不會保留狀態。
myApp.factory('MyService', function() {
var appts = AppointmentResource.getAll({
.....(params)
});
return {
appts: appts
};
});
然后在您的控制器中,您可以做..
$scope.appts = MyService.appts;
當您重新加載控制器時,服務中的appts變量將不會重新加載,並且數據將被保留。 從角度文檔 ...
“最后,重要的是要意識到所有Angular服務都是應用程序單例。這意味着每個注入器只有給定服務的一個實例。”
通常,當要保留狀態時,單例就是解決方案。
感謝Charlie Martin對於單例服務的想法。
我創建約會服務
.factory('appointmentService', function (AppointmentResource, dateSharedService, doctorSharedService) {
appointmentService = {};
appointmentService.reloadAppts = function() {
appointmentService.appts = AppointmentResource.getAll({
filterFirstDate: dateSharedService.firstDate,
filterSecondDate: dateSharedService.secondDate,
doctorIds: doctorSharedService.doctorIds
});
};
appointmentService.appts = AppointmentResource.getAll({
filterFirstDate: dateSharedService.firstDate,
filterSecondDate: dateSharedService.secondDate,
doctorIds: doctorSharedService.doctorIds
});
return appointmentService;
});
因此,這是控制器代碼的一部分:
function AppointmentsSummaryController($scope, appointmentService) {
$scope.appts = appointmentService.appts;
$scope.$on('firstDateChanges', function () {
appointmentService.reloadAppts();
$scope.appts = appointmentService.appts;
});
$scope.$on('secondDateChanges', function () {
appointmentService.reloadAppts();
$scope.appts = appointmentService.appts;
});
.....
}
最初加載控制器時,將獲得默認約會,該約會將在今天開始。 如果作用域中的參數發生了變化,則約會服務會從另一個注入的服務(dateSharedService,doctorSharedService)中獲取約會服務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.