2013-12-16 188 views
0

我有兩個文件foo.js和foo.html。Angularjs的異步API請求

在foo.js我從一個API的信息(我認爲它的異步)和foo.html有權訪問該對象。

<tr data-ng-repeat="y in vm.apidata"> 
            <td>{{y.name}}</td> 
            <td>{{y.is_closed}}</td> 
           </tr> 

但是在這裏我什麼也看不見。 代碼沒有錯誤表明我將信息當作對象的數組。

我正確地從API獲取信息,但vm.apidata未初始化,因此我可以在foo.html中顯示它。

我如何確保它已被顯示?

+0

聲明'vm'就像'var vm = {}; vm.apidata = []' – Satpal

+0

我們能否看到您的控制器的javascript – Tom

+1

請記住,如果您的異步數據檢索代碼不在Angular循環中,您必須具體調用範圍$ digest/$適用於警告Angular觸發髒檢查更改。Angular控制着UI的整個迴流,並且可能不知道外部非Angular JavaScript引入的更改。 – cbayram

回答

0

@Aqsan,我會在回答中寫了,因爲它會太冗長的評論。

我的假設是,您必須調用$ scope。$ digest/$ apply()在您的外部代碼完成其任務或可能只要感興趣的對象vm.apidata發生變異。

重要提示:Angular期望vm.apidata是一個範圍對象。簡單地放在全局窗口/自己的範圍不是你的標記所引用的。

window.vm.apidata!= scope.vm.apidata

如果你確實是正確更新範圍的節點,您可以使用相同的範圍內引用調用範圍。$適用()。

但是,如果你不在下面是一些信息。 瞭解更多關於Scopes

你可以注入到$ rootScope,這是你的服務的頂層根範圍(供應商,工廠),控制器指令引用。分層的興趣同樣$範圍控制器指令相關,並且可以用隔離範圍之外,可以在自定義的實現有注入從而範圍對象繼承(向下級聯)在父子層次結構例如,在ng-repeat指令的情況下。我要給你一個骨架的控制器(爲簡單起見)實現,你不妨把實現連接:

var myModule = angular.module('myModule', []); 

// This is a Service 
// observe how you inject the root scope 
// the array wrapper around the factory is for JS code minification protection which might name your parameter to something shorter and make it invalid (AngularJS-wise) 
myModule.factory('retrieveService', ['$rootScope', '$q', function($rootScope, $q) { 
    function retrieve(){ 

    // perhaps return a promise using the injected (light-weight) angular $q service 
    var deferred = $q.defer(); 

    // Your external code can go in here for retrieval 
    // When your async code complete call for success 
    deferred.resolve(<yourapidata>); 

    // alternatively for error 
    deferred.reject(<yourerror>); 

    // of course you could also just set the value to the $rootScope.vm.apidata here and call $apply 
    $rootScope.vm.apidata = <yourapidata>; 
    $rootScope.$apply(); 


    return deferred.promise; 

    } 
    return retrieve; 
    }]); 

// This is a Controller 
myModule.controller('MyCtrl', ['$rootScope', '$scope', 'retrieveService', '$q', function(rootScope, $scope, retrieveSvc, $q) { 

    function retrieve(){ 
    // Your external code could go in here inside the controller too 
    // upon async retrieval perhaps... 
    $scope.vm.apidata = <yourvalue> 
    } 
    // given you take care of your async call using promises and/or callbacks 
    retrieveService().then(function(apidata) { 
    $scope.vm.apidata = apidata; 
    // though $scope is recommended imho, alternatively 
    // you could bind the vm.apidata to $rootScope (here or in your service) as well which $scope will inherit 
    $rootScope.vm.apidata = apidata; 
    }); 

}]) 

有很多東西要學/擴大和排列是巨大的,但希望這給你一個很好的大方向。 $http根據你的後端API,角度服務可能是一個不錯的選擇。

+0

我已經解決了它,而不是以這種方式精確,但再次使用$範圍。 $ scope.apidata從api獲取異步返回後,$ scope。$ apply已完成。然後我可以在我的用戶界面中看到返回的數據。謝謝! – Asqan