2014-01-14 85 views
0

我有一個服務和一個位指示一個角應用程式:AngularJS - 訪問在另一個方法返回範圍方法變量

service.js

.factory('MyService', function ($http, $q) { 
    var api_url = 'http://localhost/api/'; 

    var MyService = { 

     list: function (items_url) { 
      var defer = $q.defer(); 
      $http({method: 'GET', 
       url: api_url + items_url}). 
       success(function (data, status, headers, config) { 
        defer.resolve(data); 
       }).error(function (data, status, headers, config) { 
        defer.reject(status); 
       }); 
      return defer.promise; 
     }, 
     ... 
    } 
}); 

controller.js

.controller("ItemsCtrl", function ($scope, MyService) { 

    $scope.getItems = function() { 
     MyService.list('items/').then(function(data) { 
      $scope.items = data; 
     }); 
    }; 

    $scope.addItems = function() { 
     $scope.getItems(); 

     // why is this undefined ??!!! 
     console.log($scope.items); 
    }; 

問題是我想調用中的​​方法方法。我是否需要使用$scope.apply(),因爲返回的值是一個承諾?

我想我在這裏顯示是一個普遍缺乏瞭解:/

任何幫助將非常感激。

回答

3

更改您的控制器是這樣的:

.controller("ItemsCtrl", function ($scope, MyService) { 

    $scope.getItems = function() { 
     return MyService.list('items/').then(function(data) { 
      $scope.items = data; 
     }); 
    }; 

    $scope.addItems = function() { 
     $scope.getItems().then(function() { 

      // should be what you want this time 
      console.log($scope.items); 

     }); 
    }; 

你的問題是,當你調用$scope.getItems(),HTTP響應尚未恢復,所以$scope.items不填充。您必須等待所有承諾才能解決訪問items

0

$scope.items未定義,因爲$http異步通信。也就是說,當您撥打$scope.addItems()時,它會創建併發送請求以檢索您的項目列表,然後立即轉到下一行代碼,即將$scope.items記錄到控制檯。由於$scope.items中沒有任何內容,因此您會得到一個未定義的值。

如果您想對由http調用返回的數據進行操作,您必須保證數據將被填充。換句話說,您要在$scope.items上執行的任何操作都應在您的.then()塊中調用。

$scope.$apply()用於在AngularJS上下文中未執行時強制AngularJS框架評估表達式。它在這裏不會幫助你 - 你會得到一個「已經在進行中的$摘要」的錯誤,或者是這方面的一些東西。

試試這個:

.controller("ItemsCtrl", function ($scope, MyService) { 

    $scope.getItems = function() { 
    MyService.list('items/').then(function(data) { 
     $scope.items = data; 
     console.log($scope.items); 
    }); 
    }; 

    $scope.addItems = function() { 
    $scope.getItems(); 
    }; 
}); 
0

這是因爲​​是異步的。您的回調(通過此時添加)在執行$scope.addItems之後調用。

相關問題