2015-04-29 32 views
6

您好我正在嘗試使用import.io刮一些足球比分。我設法讓他們的JS使用API​​並提供數據。問題在於它必須在控制器的私人範圍內,因爲我無法對其進行重複操作。從第三方庫異步回調更新AngularJS範圍

任何人都可以告訴我爲什麼,如果任何人有一個很好的指導範圍,可能會更有用。

latestScores.controller('ScoresController', function ($scope) { 
    $scope.pots = []; 
    var io2 = new importio("XXX", "XXXXXX[API KEY]XXXXXXXX", "import.io"); 


    io2.connect(function (connected) { 

     if (!connected) { 
      console.error("Unable to connect"); 
      return; 
     } 


     var data; 


     var callback = function (finished, message) { 

      if (message.type == "DISCONNECT") { 
       console.error("The query was cancelled as the client was disconnected"); 
      } 

      if (message.type == "MESSAGE") { 
       if (message.data.hasOwnProperty("errorType")) { 

        console.error("Got an error!", message.data); 
       } else { 
        data = message.data.results; 
       } 
      } 
      if (finished) { 

       pots = data; 
       console.log(pots); /* This gives me an object */ 
     } 
     } 
     io2.query({ 
     "connectorGuids": [ 
     "d5796d7e-186d-40a5-9603-95569ef6cbb9"], 
    }, callback); 
    }); 
    console.log($scope.pots); /* This gives me nothing */ 
}); 
+3

你asigning數據到本地變量盆,嘗試將其分配給$回調scope.pots – ecyshor

+0

@NicuReut不是本地 - 花盆 - 在窗口中是全局變量:-) – Grundy

回答

2

angularjs數據綁定無法知道何時在第三方庫的回調中更新範圍。

在你的回調,這樣做:

$scope.pots = dataReceived 
$scope.$apply(); 

如果你想跳過調用$ scope.apply(),你需要使用的角度自己的諾言模塊(稱爲$ Q)和包裝你的API調用到一項服務。另外,如果你的API是基於websocket的,你應該訂閱$ scope.on('$ destroy')事件以在控制器不在時斷開與你的api的連接。

+1

謝謝你,是的,我之前使用過承諾,但是因爲這是第三方模塊,所以它把我扔掉了。 – craigie2204

1

ng-repeat有它自己的範圍。 在您的情況下,您將數據分配給本地變量,而不是將其分配給範圍變量。

變化這段代碼

if (finished) { 

       pots = data; 
       console.log(pots); /* This gives me an object */ 
     } 

if (finished) { 

       $scope.pots = data; 
       console.log($scope.pots); /* This gives me an object */ 
     }