我有两个REST Web服务,我必须逐个调用。第一个返回一些我必须用于第二个REST服务调用的数据。第二个结果,我需要将它提供给我的指令,它应该显示值。
我以这种方式使用AngularJS构建控制器:
app.controller('MyRestCtrl', [$scope, 'RestScope', function($scope, RestScope) {
RestScope.preGet().success(function(data) {
/* success of the first REST call and do some calculations with this data */
/* Question: I have to set the calculated data (data1 and data2) to the
RestScope provider, how can I do this, so that the second call
.get() has this data to make the request? */
RestScope.get().success(function(response) {
/* response has all the data which I need for my directive */
/* Question: How can I provide this data into my directive? */
});
})
}]);
这是提供商:
app.provider('RestScope', function() {
this.data1 = null;
this.data2 = null;
this.setData1 = function(_data1) {
this.data1 = _data1;
}
this.setData2 = function(_data2) {
this.data2 = _data2;
}
this.$get = ['$http', '$log', function($http, $log) {
var _data1 = this.data1;
var _data2 = this.data2;
function get() {
return $http.get('http://www.test.com/' + _data1 + '/?param=' + _data2);
}
function preGet() {
return $http.get('http://www.test.com/getData/');
}
return {
get: get,
preGet: preGet
};
}];
});
这是我的指令:
app.directive('myDirective', function() {
return {
restrict: 'AEC',
replace: false,
templateUrl: 'path/to/my.html'
};
});
首先,如何将preGet().success
内部的一些数据设置到RestScope
提供商?第二个问题,如果我得到第二个电话get().success
的数据如何将其提供给我的指令?