0
我是angularjs的新手。我想以显示从一个控制器到另一个 这Ajax响应是控制器1将数据从一个控制器全局存储到另一个控制器使用服务
app.controller("currentTaskCtrl", function ($scope, $http, $rootScope, currentTaskService) {
$scope.currentTaskTab = function() {
$http({
url: '/index/tasktimer',
method: 'POST',
data : {"currentTask": "current"},
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}
}).success(function(response) {
currentTaskService.saveData(response.task_name, response.estimated_hours, response.time_remaining, response.start_date, response.stop_date, response.actual_hours);
}).error(function(response) {
$scope.codeStatus = response || "Request failed"
});
}
});
这是控制器2
app.controller("currentTaskTabCtrl", function ($scope, $rootScope, currentTaskService) {
$rootScope.$on('currentTaskService', function() {
$scope.data = currentTaskService.getData();
});
});
这是服务
app.service('currentTaskService', function($rootScope) {
this.saveData = function(tname, estimated_hours, time_remaining, start_date, stop_date, actual_hours) {
// Here the data gets saved in $rootScope.data
}
this.getData = function() {
return data;
}
});
这是HTML代码(控制器2)数据得到显示
<div ng-controller="currentTaskTabCtrl">
<table>
<thead>
<tr>
<th> # </th>
<th> Task Name </th>
<th> Estimated Hours </th>
<th> Time Remaining </th>
<th> Start Date </th>
<th> Stop Date </th>
<th> Actual Time </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="task in data">
<td></td>
<td>{{task.task_name}}</td>
<td>{{task.estimated_hours}}</td>
<td>{{task.time_remaining}}</td>
<td>{{task.start_date}}</td>
<td>{{task.stop_date}}</td>
<td>{{task.actual_time}}</td>
</tr>
</tbody>
</table>
</div>