API完成时的Initialise指令

时间:2015-01-06 12:06:04

标签: javascript angularjs angularjs-directive

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

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

2 个答案:

答案 0 :(得分:1)

一种可能的解决方案是,您可以使用ng-if指令在API完成时创建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和控制器。

答案 1 :(得分:0)

解析路由器中的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获得上述代码,因此请查看更多详细信息。

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

相关问题