简体   繁体   中英

Inject Service into Directive AngularJS and data binding.

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.

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
});

You can do this also ,

return $q(function (resolve, reject) {

    $http({
        method: 'GET',
        url: 'urlToDataJson'
        }).then(function(resp){
            $scope.responseDate = resp.data;
            resolve(responseData);
        });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM