2015-06-20 35 views
0

我有,做現場API調用下面的工廠方法的angularjs應用:Angularjs結合Ajax的返回值

//Return SP json by SPID 
    azureMobileClient.getSPjsonBySPID = function (callback, spid) 
    { 
     azureMobileClient.azureMSC.invokeApi("get_spjson_byspid", { 
      parameters: { 
       spid: spid 
      }, 
      method: "get" 
     }).done(function (results) { 
      //console.log(results.result); 

      callback(results.result); 
     }, function (error) { 
      alert(error.message); 
     }); 
    } 

和我有以下控制器的方法,該方法使用它

$scope.getSPName = function (spid) 
    { 

     console.log("SPID:", spid); 

     var returnedName; 

     AzureMobileClient.getSPjsonBySPID(function (item) 
     { 
      console.log("item.fullname:", item.fullname); 
      returnedName = item.fullname; 


     }, spid); 

     return returnedName; 
    } 

而且這是我目前如何嘗試綁定返回的item.fullname(在ng-repeat中):

<p> 
{{getSPName(t.parsedjsondata.SPId)}} 
</p> 

問題是綁定不起作用,雖然我確實看到了console.log()的值與正確的item.fullname。我猜這與API調用的延遲有關,我需要在某處插入$scope.$apply(),但我不知道該怎麼做。

+0

你真的應該嘗試使用承諾($ q)。以下是有關如何使用$ q.defer()的示例代碼:https://medium.com/javascript-jquery-angular-firebase-and-mongodb/angular-s-q-defer-example-78867ecfa7d8 –

回答

0

嘗試此操作,看起來像是錯誤地綁定了{{}}使用變量來解析值。

<p> 
{{SPName}} 
</p> 

$scope.getSPName = function (spid) 
    { 

     console.log("SPID:", spid); 

     var returnedName; 

     return AzureMobileClient.getSPjsonBySPID(function (item) 
     { 
      console.log("item.fullname:", item.fullname); 
      returnedName = item.fullname; 
      return returnedName; 
     }, spid); 


    } 
$scope.SPName = $scope.getSPName(t.parsedjsondata.SPId) 
+0

仍然無效。我可以看到在console.log中檢索到的item.fullname的值,但它並未綁定到視圖。我確信這是因爲該值是從一個實時服務器中檢索出來的,並且我需要調用$ scope。$ applay(),但我不確定如何在我的方法中使用'return'語句調用它 – Eyad

+0

更新了答案 – vinayakj

2

代碼中存在一些不好的做法。一些建議:

  1. 在工廠方法中使用承諾,即$ q。
  2. 儘量不要在表達式中使用昂貴的函數{{}}。他們經常被評估爲Angular的骯髒檢查過程的一部分。

一個爲您解決問題的辦法是改變你的角度服務函數返回一個承諾:

azureMobileClient.getSPjsonBySPID = function (spid) 
{ 
    var deferred = $q.defer(); 
    azureMobileClient.azureMSC.invokeApi("get_spjson_byspid", { 
     parameters: { 
      spid: spid 
     }, 
     method: "get" 
    }).done(function (results) { 
     //console.log(results.result); 
     deferred.resolve(results.result); 
    }, function (error) { 
     alert(error.message); 
     deferred.reject(error); 
    }); 
    return deferred.promise; 
} 

然後在你的控制器做這樣的事情:

$scope.spName = null; 
azureMobileClient.getSPjsonBySPID(spid).then(function(item){ 
    $scope.spName = item.fullname; 
}, function(error) { 
    // Show error 
});