我有这个与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控制台时,我看到包含披萨的日志和正确的数字&#34;总计&#34;附在最后。
以下是HTML视图:
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1>{{borough}}</h1>
<p>{{mvcTotal}} motor vehicle collisions</p>
</div>
</div>
</div>
答案 0 :(得分:0)
您要对数据库调用返回的数据执行的操作必须在完成函数内完成。我想你理解这一点,但你缺少的是操作的顺序。使用调试器查看代码执行的实际顺序:
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;