簡體   English   中英

將服務注入指令AngularJS和數據綁定。

[英]Inject Service into Directive AngularJS and data binding.

我創建了一個使用$ http獲取數據的服務,並將此數據存儲在此Service的變量中,還創建了一個指令,該指令使用該服務創建帶有選項的標簽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調用返回一個promise對象。 $http調用包裝到函數中並返回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);
        });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM