0

我有这个与 CartoDB 一起使用的代码。假设使用他们的 JS 库运行查询,然后返回一些数据。我正在添加一些结果,它在 done() 函数中工作。虽然第二次我尝试在 AngularJS 中使用/设置结果作为范围变量,但我失去了它。这是一些示例代码。 编辑:抱歉,“不起作用”意味着我总是得到 mvcTotal = 0 的默认值,而不是 JS 内部计算的值。

angular.module('angMvcApp')
  .controller('DataCtrl', ['$scope', '$routeParams', function ($scope, $routeParams) {
    var borough = $routeParams.borough;

    var sql = new cartodb.SQL({user: 'wkaravites'});
    var table = 'qiz3_axqb';
    var mvcTotal = 0;

    if (borough != null) {
      $scope.borough = borough;
    } else {
      $scope.borough = "Data Overview";

      sql.execute("select borough, count(*) from qiz3_axqb group by borough")
        .done(function (data) {
          $.each(data.rows, function (index, value) {
            console.log("pizza: " +value['count']);
            mvcTotal += value['count'];
            //$('#' + value['borough'] + '').text(value['count']);
            //$('#boroughList').append('<h2>' + value['borough'] + '</h2>');

          });
          //I see this correct
          console.log(mvcTotal +" totals");

          //This doesn't work
          $scope.mvcTotal = mvcTotal;

        })
        .error(function (errors) {
          // errors contains a list of errors
          console.log("errors:" + errors);
        });
      console.log(mvcTotal+" test test");

      //This doesn't work
      $scope.mvcTotal = mvcTotal;

      //This works
      #scope.mvcTotal = 57;

    }


  }]);

我是否搞砸了如何将常规变量转换为 Angular 范围变量?当我检查 JS 控制台时,我看到了包含比萨饼的日志,并且在末尾附加了“总计”的正确数字。

这是 HTML 视图:

<div class="container">
  <div class="row">
    <div class="col-lg-12">
      <h1>{{borough}}</h1>
      <p>{{mvcTotal}} motor vehicle collisions</p>
    </div>
  </div>
</div>
4

1 回答 1

0

您想要对从 DB 调用返回的数据执行的任何操作都必须在 done 函数内部完成。我想你明白这一点,但你缺少的是操作的顺序。使用调试器查看代码执行的实际顺序:

var sql = new cartodb.SQL({user: 'wkaravites'});

//step #1
var mvcTotal = 0;

  //step #2
  sql.execute("select borough, count(*) from qiz3_axqb group by borough")
    .done(function (data) {
      //step #6 finally after DB responds this is called. mvcTotal is still 0
      //$scope.mvcTotal is 57
      $.each(data.rows, function (index, value) {
        console.log("pizza: " +value['count']);
        mvcTotal += value['count'];


      });
      //step #7 now you get the correct total
      console.log(mvcTotal +" totals");

      //step #8 this is correct. you can display this value in your html view as {{mvcTotal}}
      $scope.mvcTotal = mvcTotal;

    })


  //step #3 mvcTotal is still 0
  console.log(mvcTotal+" test test");


  //step #4 mvcTotal is still 0 since DB call has not finished
  $scope.mvcTotal = mvcTotal;

  //step #5 previous value was 0, now it's 57
  $scope.mvcTotal = 57;
于 2016-09-23T16:15:01.333 回答