有人可以解释为什么运行 for 循环后$scope.shopLocation 不会更改为 = special。我需要在控制器中进一步访问此 var 数据,但我无法在 http.get 中访问它
如果有人有任何指向范围/变量等良好解释的链接,我将不胜感激。
.controller('MapCtrl', function($scope, $http) {
$scope.shopLocation = [];
$http.get('/x/xx/xxx/advertsearch_json.php')
.then(function(res) {
$scope.jobs1 = res.data;
var special = [];
var categories = [];
for ( var i=0; i < $scope.jobs1.length; i++ )
categories[$scope.jobs1[i]['CHCO_LOCATION']] = $scope.jobs1[i];
$scope.jobs1 = new Array();
for ( var key in categories )
special.push(categories[key]);
$scope.shopLocation = special;
});
})
问题是您没有确保其余的逻辑仅在异步操作完成后发生。您需要做的是在http
调用的then
函数中return
所需的信息,然后使用对 promise 的引用来获取该返回值。它的工作原理是这样的:
var myPromise = $http.get('whatever').then(function(resp) {
// do what you need to do
return something; // return the value you'll need later
});
// elsewhere
$scope.foo = function() {
myPromise.then(function(something) {
// use the value you returned ^. the logic here will run when the value is definitely available.
});
};
这样,如果您调用 $scope.foo
,您的逻辑肯定会具有可用的异步操作的值。将其与以下代码进行对比:
$scope.something;
$http.get('whatever').then(function(resp) {
$scope.something = //whatever
});
$scope.foo = function() {
console.log($scope.something); // no guarantee this will be set
};
您的异步代码导致更新发生在摘要周期之外。因此,该值正在更改,但您不会在屏幕上看到它。
在这种情况下,您需要应用范围 - 因此在$scope.shopLocation = special;
之后添加:
$scope.$apply();
我认为这与特殊范围有关。 在http.get完成后,它被销毁了。 您实际上并没有复制您提供的代码中的内容。 你应该做一个深拷贝。 https://docs.angularjs.org/api/ng/function/angular.copy
.controller('MapCtrl', function($scope, $http) {
$scope.shopLocation = [];
$http.get('/x/xx/xxx/advertsearch_json.php')
.then(function(res) {
$scope.jobs1 = res.data;
var special = [];
var categories = [];
for ( var i=0; i < $scope.jobs1.length; i++ )
categories[$scope.jobs1[i]['CHCO_LOCATION']] = $scope.jobs1[i];
$scope.jobs1 = new Array();
for ( var key in categories )
special.push(categories[key]);
$scope.shopLocation = angular.copy(special);
});
})
所以这就像调用后面的函数一样简单,该函数使用"then"中的新数据
$http.get('/pb3/corporate/Apostrophe/advertsearch_json.php')
.then(function(res) {
$scope.jobs1 = res.data;
var special = [];
var categories = [];
for ( var i=0; i < $scope.jobs1.length; i++ )
categories[$scope.jobs1[i]['CHCO_LOCATION']] = $scope.jobs1[i];
$scope.jobs1 = new Array();
for ( var key in categories )
special.push(categories[key]);
$scope.shopLocation = special;
**createPoints();**
});
感谢大家的帮助