【问题标题】:Initialise directive when API is doneAPI 完成时初始化指令
【发布时间】:2015-01-06 12:06:03
【问题描述】:

我有一个指令,它的数据取决于 API 响应。因为$compile的指令是在API完成之前运行的,所以指令状态是错误的。

我该如何解决这个问题? AngularJs 中是否有指令、控制器或任何内容的配置会告诉元素等待 API 完成?

【问题讨论】:

  • 没有例子就无法判断。指令中的哪种状态是依赖的?
  • 如果可能的话,你能把部分代码贴出来吗?
  • 在API完成之前是否可以不加载输入路由的html?

标签: javascript angularjs angularjs-directive


【解决方案1】:

一种可能的解决方案是,您可以在 API 完成后使用 ng-if 指令创建 dom。

<your-directive ng-if="isAPIExecuted"></your-directive>

在您的 API 成功处理程序中,

Test.get().then(function(){
   $scope.isAPIExecuted = true;
});

编辑:

如果你使用的是ui-router,那么一旦API被执行就加载你的html,你可以解决如下:

.state{
  controller: '',
  templateUrl: '',
  resolve: {
            data: function($q, $timeout){
                // Replace this code with your API call

                var deferred = $q.defer();
                $timeout(function(){
                    return deferred.resolve();
                },10000);

                return deferred.promise;
            }
        }
}

因此,只有在您的承诺得到解决后,它才会加载 html 和控制器。

【讨论】:

    【解决方案2】:

    解析路由器中的API调用,例如:

    $routeProvider
    .when("/news", {
        templateUrl: "newsView.html",
        controller: "newsController",
        resolve: {
            message: function(messageService){
                return messageService.getMessage();
        }
    }
    

    })

    然后你可以在控制器中注入resolve属性:

    app.controller("newsController", function (message) {
        $scope.message = message;
    });
    

    http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx 获得上述代码,请查看该代码以了解更多详情。

    如果您想要更具体的内容,请提供一些代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多