【问题标题】:How use data returned by jquery.ajax in ng-repeat?如何在 ng-repeat 中使用 jquery.ajax 返回的数据?
【发布时间】:2016-08-08 08:20:22
【问题描述】:

这是我的 jquery ajax 调用

jQuery.ajax({
            url: view_url+"get_messagekinds",
            success: function (result) {
                $scope.response = result;
            },
            async: false
        });

这里是html代码:

<select id="select_msg_kind"
                    name="select_msg_kind"
                    class="form-control"
                    ng-model="message_kind_selected" style="height:30px;width:220px">
                    <option value="0">--Select Message Kind--</option>
                    <option ng-repeat="res in response track by $index" value="{{ res.id }}">
                        {{ res.name }}
                    </option>
                </select>

但选择列表为空。这是截图

如何使用 ng-repeat 使用 ajax 调用返回的数据填充选择列表?

这里是ajax调用返回的数据:

[{"id": 1, "name": "Test1"}, {"id": 2, "name": "test2"}, {"id": 3, "name": "Test3"}]

【问题讨论】:

  • 请把ajax的结果也加进去
  • @guradio 更新了我的问题
  • 提示:不要使用jQuery.ajax,而是使用angular的$http-service。后者会注意到应该运行所谓的“消化循环”的角度
  • 我需要同步调用。你能给我 angularjs 的同步代码吗,因为我已经搜索过但没有找到任何令人满意的解决方案
  • @ShoaibAkhtar 您永远不需要也不应该在 JavaScript 中使用任何同步 AJAX 调用 this SO answer 可能会帮助您找到更好的方法。

标签: jquery angularjs ajax angularjs-ng-repeat


【解决方案1】:

提示:不要使用 jQuery.ajax,而是使用 Angular 的 $http-service。后者会注意到一个所谓的“消化循环”应该运行的角度:

$http.get(url).then(function(result) {
    // success
    $scope.response = result;
}, function() {
    // error
});

如果你真的要使用jquery的ajax(我想你的原因是因为你使用async: false),你应该自己触发digest循环:

jQuery.ajax({
    url: view_url+"get_messagekinds",
    success: function (result) {
        // trigger digest cycle with '$apply'
        $scope.$apply(function() {
            $scope.response = result;
        });
    },
    async: false
});

但是,您不应该使用异步,您可以只使用 $http 服务的承诺和回调函数。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-10
  • 1970-01-01
  • 2011-05-13
  • 2017-09-08
  • 2015-05-19
  • 1970-01-01
相关资源
最近更新 更多