本文介绍了AngularJS 资源承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 $resource 的简单控制器:

I've got a simple controller that use $resource :

 var Regions = $resource('mocks/regions.json');

 $scope.regions = Regions.query();

我在指令中使用这个控制器(在链接函数中)

I'm using this controller in a directive (in the link function)

var regions = scope.regions;

但是区域是未定义的.调用是异步的,这是非常合乎逻辑的.

But regions is undefined. It's pretty logic the call is asynchronous.

我的问题是我该如何等待结果和区域成为包含所有数据的数组?

My question is how can i do to wait the result and regions be an array with all data ?

UPDATE :

这里是指令的定义

app.directive('ngMap', function() {
  return {
    restrict: 'EA',
    replace: 'true',
    scope: {

    },
    template: '<div id="map"></div>',
    controller: 'AccordMapCtrl',
    link: function(scope, element, attrs) {
      var regions = scope.regions;
      console.log(regions);

      for (var region in regions) {}
    };
  });

推荐答案

如果要使用异步方法,则需要通过 $promise 使用回调函数,示例如下:

If you want to use asynchronous method you need to use callback function by $promise, here is example:

var Regions = $resource('mocks/regions.json');

$scope.regions = Regions.query();
$scope.regions.$promise.then(function (result) {
    $scope.regions = result;
});

这篇关于AngularJS 资源承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 20:33