有人可以解释为什么$ scope.shopLocation在运行for循环后不会更改为= 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;
});
})
答案 0 :(得分:1)
我认为问题在于,您不能确保只有在异步操作完成后才会发生其余逻辑。您需要做的是在return
调用的then
函数中http
所需的信息,然后使用对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
};
答案 1 :(得分:0)
我相信你的异步代码导致更新发生在摘要周期之外。因此,值正在被更改,但您没有看到它反映在屏幕上。
在这种情况下,您需要应用范围 - 所以在$scope.shopLocation = special;
添加:
$scope.$apply();
答案 2 :(得分:0)
我认为这与特殊范围有关。它在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);
});
})
答案 3 :(得分:0)
所以这就像调用后来使用&#39;然后&#39;
中的新数据的函数一样简单 $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();**
});
感谢大家的帮助