AngularJS等待直到

5
我有:
$scope.bounds = {}

以后在我的代码中:

$scope.$on('leafletDirectiveMap.load', function(){
    console.log('runs');
    Dajaxice.async.hello($scope.populate, {
                'west' : $scope.bounds.southWest.lng,
                'east': $scope.bounds.northEast.lng,
                'north' : $scope.bounds.northEast.lat,
                'south': $scope.bounds.southWest.lat,
    });
});

作为你的助手,我可以翻译以下内容。这是一个关于编程的问题。

如您所见,在开始时边界是空的,但稍后(几毫秒)用 JavaScript 库(leaflet angular)加载。然而,$scope.$on(...) 在边界设置之前运行,因此 'west' : $scope.bounds.southWest.lng, 返回未定义变量的错误。

我想做的是等待边界(southWestnorthEast)被设置,然后运行 Dajaxice.async.hello(...)

所以我需要像“等待边界设置”这样的东西。


不确定这是否只是一个打字错误,但是你的 $scope.bound = {}; 缺少一个 's',所以 $scope.bounds. 不存在,因此未定义。或者,您应该使用 $scope.$watch('bounds',function(newVal,oldVal){ .. stuff here ..}) 来查看变量是否已更改并加载您想要的内容。 - m.e.conroy
2个回答

5
您可以使用$watch来实现此目的,例如:
 $scope.$on('leafletDirectiveMap.load', function(){

       $scope.$watch( "bounds" , function(n,o){  

           if(n==o) return;

           Dajaxice.async.hello($scope.populate, {
               'west' : $scope.bounds.southWest.lng,
               'east': $scope.bounds.northEast.lng,
               'north' : $scope.bounds.northEast.lat,
               'south': $scope.bounds.southWest.lat,                
            });

       },true);
 });

1
不知道为什么,但它能工作。我知道基本的 $watch 是做什么的,但是 if(n==o) return; 和最后的 true 是干什么用的? - Diolor
@Diolor function(n,o) 获取bounds的旧值和新值,如果它们相等,则不执行任何操作并返回。true表示:比较对象是否相等而不是引用。 - Ivan Chernykh

4
如果您想每次边界变化时都执行此操作,您应该只使用$watch表达式:
$scope.$watch('bounds',function(newBounds) {
   ...          
});

如果您只想在边界值首次设置时执行此操作,则应在完成操作后停止监视:

var stopWatching = $scope.$watch('bounds',function(newBounds) {
  if(newBounds.southWest) {
     ...
     stopWatching();
  }
});

您可以在这里看到它的实际运用:http://plnkr.co/edit/nTKx1uwsAEalc7Zgss2r?p=preview

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接