2014-02-16 26 views
4

我試圖綁定一些數據從一個API返回到我的範圍使用承諾$ q,我能夠從服務器拉數據沒有任何問題(我可以請參閱使用fiddler返回的JSON),但$ scope變量保持爲空,任何幫助將不勝感激!提前致謝。

代碼:

toDoListService.js

app.factory("toDoListService", function ($http, $q) { 
     var deferred = $q.defer(); 

     return { 
      get: function() { 

       $http({ method: 'GET', url: '/api/todo/' }). 
        success(function (data) { 
         deferred.resolve(data); 
        }). 
        error(function (data, status, headers, config) { 
         deferred.reject(status); 
        }); 
       return deferred.promise; 
      } 
}); 

toDoListController.js

app.controller("toDoListController", function($scope, toDoListService){ 
     $scope.toDoList = toDoListService.get(); 
}); 

回答

3

首先你應該把var deferred = $q.defer();get功能,讓每一個get有它自己的延期目的。

其次get實際返回是一個承諾。所以,你需要訪問你這樣的數據:

app.controller("toDoListController", function($scope, toDoListService){ 
    toDoListService.get().then(function(data){ 
      $scope.toDoList = data; 
    }); 
}); 
3

現在,您$scope.toDoList勢必一個承諾。這種綁定方式曾用於工作,但我認爲1.2已被棄用。

正如邁克爾指出,你必須做到:

app.controller("toDoListController", function($scope, toDoListService){ 
    toDoListService.get().then(function(data){ 
    $scope.toDoList = data; 
    }); 
}); 

此外,使用$q這裏不需要所有的,因爲反正$http返回一個承諾。因此,你可以只是做:

app.factory("toDoListService", function ($http){  
    return { 
    get: function() { 
     return $http({ method: 'GET', url: '/api/todo/' }); 
    } 
    }; 
}); 
2

您可以使用此簡化代碼:

toDoListService.js

app.factory("toDoListService", function ($http, $q) { 
    return { 
     get: function() { 
      return $http({ method: 'GET', url: '/api/todo/' }); 
     } 
    } 
}); 

toDoListController.js

app.controller("toDoListController", function($scope, toDoListService) { 
    toDoListService.get().then(function(response){ 
     $scope.toDoList = response.data; 
     return response; 
    }); 
}); 

一定要在成功回調中返回response,否則鏈接的承諾將不會收到。