将服务注入指令 AngularJS 和数据绑定。

Inject Service into Directive AngularJS and data binding.

我创建了一个使用 $http 获取数据的服务,并且该数据存储在该服务的一个变量中,我还创建了一个使用该服务创建带有选项的标签 select 的指令,这些选项在服务中获得,但这是我的问题,获得的数据从未与指令连接。

服务和指令:

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

使用 Chrome 的 DevTool 我可以看到 $http 运行后数据更新,但选项中未显示数据。

上面的代码是我需要做的一个例子。

您的 $http 调用 return 是一个承诺对象。将 $http 调用包装在函数和 return promise 对象中,然后在您的指令中调用此函数并解析 promise 对象并获取数据。

具体来说,

getData(){
  return $http({
       method: 'GET',
       url: 'urlToDataJson'
       }).then(function(resp){
            listOptions = resp.data
   ); // this returns a promise
}

然后在你的指令中,像这样解决承诺:

MyService.getData().then(function(data){
   console.log(data); // <-- this is how you access the result of your $http call
});

你也可以这样做,

return $q(function (resolve, reject) {

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