我是angularjs的新手。我试图显示从一个控制器到另一个控制器的ajax响应 这是控制器1
public static int[] uniqueHouseLocationsSorted(final int[] houseLocations) {
final Set<Integer> integers = new TreeSet<>();
for (int houseLocation : houseLocations) {
integers.add(houseLocation);
}
int[] unique = new int[integers.size()];
int i = 0;
for(Integer loc : integers){
unique[i] = loc;
i++;
}
return unique;
}
这是控制器2
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"
});
}
});
这是服务
app.controller("currentTaskTabCtrl", function ($scope, $rootScope, currentTaskService) {
$rootScope.$on('currentTaskService', function() {
$scope.data = currentTaskService.getData();
});
});
这是显示数据的HTML代码(控制器2)
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;
}
});
答案 0 :(得分:0)
你可以这样说:
1-将 $ rootScope 注入两个控制器
2-在代码下面将其中一个作为数据接收器实现:
$rootScope.$on('transferDataEvent', function(event, data) {
// you will receive data here
});
3-以及代码下面的另一个电话作为数据发送方
$rootScope.$emit('transferDataEvent', data); // send data
$ on 会成为一名听众 $ emit 通过范围层次结构
向上调度事件答案 1 :(得分:0)
您也可以从控制器发送数据。
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="sendData();"></button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http,$rootScope) {
function sendData($scope) {
var arrayData = [1,2,3];
$rootScope.$emit('someEvent', arrayData);
}
});
app.controller('yourCtrl', function($scope, $http,$rootScope) {
$rootScope.$on('someEvent', function(event, data) {
console.log(data);
});
});
</script>