Reputation: 239
I created a Service that obtain data with $http and this data is stored in a variable of this Service, also I created a Directive that use the service to create a tag select with options, these options were obtained in the service, but this is my problem the data obtained never connect with directive.
Service and Directive:
angular.module('myModule'[])
.factory('myService', ['$http', function($http){
var listOptions = [];
$http({
method: 'GET',
url: 'urlToDataJson'
}).then(function(resp){
listOptions = resp.data
})
;
return {
list: listOptions;
}
}]
.directive('myDirective', ['myService', function(myService){
restrict: 'E',
template: '<select ng-options="item.id as item.name for item in list"></select>',
replace: true,
controller: ['$scope', function($scope)
$scope.list = MyService.list;
]
}])
;
with the Chrome's DevTool I can see data is updated after $http runs, but the data not shown in the options.
The code above is an example that I need to do.
Upvotes: 0
Views: 130
Reputation: 1907
You can do this also ,
return $q(function (resolve, reject) {
$http({
method: 'GET',
url: 'urlToDataJson'
}).then(function(resp){
$scope.responseDate = resp.data;
resolve(responseData);
});
});
Upvotes: 0
Reputation: 882
Your $http
call returns a promise object. Wrap the $http
call in a function and return the promise object, then, in your directive, invoke this function and resolve the promise object and get the data.
Specifically,
getData(){
return $http({
method: 'GET',
url: 'urlToDataJson'
}).then(function(resp){
listOptions = resp.data
); // this returns a promise
}
And then in your directive, resolve the promise like so:
MyService.getData().then(function(data){
console.log(data); // <-- this is how you access the result of your $http call
});
Upvotes: 1