2014-09-11 29 views
-1

此片段使用AngularJS,jQuery和ASP.NET將數據從服務器移動到客戶端。因此,在我添加$ .getJSON之前,我只有一行代碼$ scope.cards = // array完成回調中的getJSON有效數據無法查看

當我添加jSON調用時,硬編碼的$ scope不會查看。我在客戶端控制檯中也沒有看到任何錯誤。有任何想法嗎?

var cardsListController = function ($scope) { 

    var uri = 'api/products'; 

    $.getJSON(uri) 
    .done(function (data) { 
     // On success, 'data' contains a list of products. 
     $scope.cards = [{ Id: 1 }, { Id: 2 }]; //**** this works if i move outside this method 
    }); 

};

<!DOCTYPE html> 
<html ng-app xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <title></title> 
    <script src="Scripts/angular.js"></script> 
    <script src="cardsController.js"></script> 
    <script src="Scripts/jquery-2.1.1.js"></script> 
</head> 
<body ng-controller="cardsListController"> 
    <div id="cardsListController"> 
     <div ng-repeat="card in cards"> 
      Card {{card.Id}} 
     </div> 
    </div> 
</body> 
</html> 
+0

您需要使用'$範圍。$應用()'。在完成方法,因爲你正在從jquery ajax更新作用域,因爲如果角色不得不運行其摘要循環,angular就不知道外部發生的事情。 _但理想情況下,你應該只是使用角提供的ajax服務,$ http或$資源,所以你不必這樣做,是一個更好的做法_ – PSL 2014-09-11 02:41:21

+0

你可以使用$ http get方法從服務器檢索數據,你試過了嗎? – Shohel 2014-09-11 02:48:17

+0

你可以給我你的服務器代碼嗎? – Shohel 2014-09-11 02:49:10

回答

0

您需要使用的角度$http service.get()的AJAX或使用$scope.$apply()通知angularjs運行其手錶

var cardsListController = function ($scope, $https) { 

    var uri = 'api/products'; 

    //using angularjs 
    $https.get(uri, { 
     responseType: 'json' 
    }).success(function() { 
     $scope.cards = [{ 
      Id: 1 
     }, { 
      Id: 2 
     }]; 
    }); 

    $.getJSON(uri) 
     .done(function (data) { 
     // On success, 'data' contains a list of products. 
     $scope.cards = [{ 
      Id: 1 
     }, { 
      Id: 2 
     }]; //**** this works if i move outside this method 

     //inform angular js to apply its watches so that the view will get updated 
     $scope.$apply(); 
    }); 
};