【问题标题】:getJSON valid data in done callback doesn't make it to view完成回调中的 getJSON 有效数据无法查看
【发布时间】:2014-11-04 20:34:13
【问题描述】:

这个 sn-p 使用 AngularJS、jQuery 和 ASP.NET 将数据从服务器移动到客户端。所以在我添加 $.getJSON 之前,我只有一行代码 $scope.cards = //array

当我添加 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>

【问题讨论】:

  • 您需要在 done 方法中使用$scope.$apply(),因为您正在从 jquery ajax 更新范围,因为 Angular 不知道如果它必须运行其摘要循环,则外部发生的事情。 但理想情况下,您应该只使用 Angular 提供的 ajax 服务、$http 或 $resource,这样您就不必这样做,这是一种更好的做法
  • 你可以使用$http get方法从服务器获取数据,你试过吗?
  • 你能给我你的服务器代码吗?

标签: jquery angularjs asp.net-web-api


【解决方案1】:

你需要使用 angular $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();
    });
};

【讨论】:

    猜你喜欢
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 2016-09-27
    • 2011-02-18
    • 2012-06-02
    • 1970-01-01
    • 2011-12-15
    相关资源
    最近更新 更多