angular:为什么不用来自ajax调用的数据进行ng-repeat更新?

时间:2015-02-12 09:18:25

标签: ajax angularjs ng-repeat

从控制器执行ajax调用。可以从同一个html模板中的两个不同链接触发调用。使用上面切换到选项卡的链接时,ajax调用返回的数据会正确显示。使用refresh链接时,ng-repeat中的元素不会更新。谁知道为什么会这样?

angularjs:

app.controller("ActiveSimulations",
    ["$scope", "$http", "socket",
    function($scope, $http, socket){

        $scope.active_simulations_dict = {};
        $scope.get_active_simulations = function() {
            var responsePromise = $http.get("/active_simulations");
            responsePromise.success(function (data, status, headers, config) {
                $scope.active_simulations_dict = data;

                console.log($scope.active_simulations_dict)
            });
            responsePromise.error(function (data, status, headers, config) {
                console.log('Warning - "AJAX failed!"')
                alert("AJAX failed!");
            });
        };
}]);

HTML

<div id="followSim" class="tab-pane fade">
  <h3>Follow running simulations</h3>
  <div class="inline-containers">
    <div id="simulation-list-wrapper">
      <ul class="list-unstyled">
        <li ng-repeat="(key, value) in active_simulations_dict">
          <a ng-show="value[0] && value[2]" ng-click="followActiveSimulation(key)">
            {[{ value[0] }]} ( {[{ value[2] }]} is director)
          </a>
        </li>
      </ul>
    </div> <!--end simulation list wrapper-->

    <div id="refresh-simulation-list" ng-controller="ActiveSimulations">
        <a id="refresh-link"
           class="right-side"
            ng-click="get_active_simulations()">
          <i class="icon-refresh right-side"></i>
          refresh list
        </a>
    </div>

1 个答案:

答案 0 :(得分:1)

正如@kasoban指出的那样,你可能会遇到多个实例的问题。最佳做法是创建一个处理请求的服务。您可以注入它并从任何控制器调用请求函数,例如:

$scope.active_simulations_dict = RequestService.get_active_simulations();