使用指令范围中的参数从 Angular 指令中的服务加载数据

Load Data from Service in Angular Directive using Parameter from Directive Scope

我有以下代码用于 angular 指令:

directive('searchTerms', ['$http', function ($http) {
            return {
                scope: { model: "=ngModel", metaDataUrl: "@metaData" },
                templateUrl: 'infohelper/SearchTermsTemplate',
                link: function ($scope) {...}
                controller: function ($scope) {...}
            }
}

对于指令的每次使用,都会将不同的 URL 传递给 $scope 变量 metaDataUrl。基于不同的元数据应该通过 $http 服务加载。我的问题是:如何确保在 link 函数之前加载元数据? $routeProvider 服务中是否有类似于 resolve 选项的东西可以用于指令?

$http returns 一个承诺,因此一旦响应在您的 link 函数中准备就绪,您就可以异步管理响应。

如果没有,您可以在 link 函数中声明一个观察者。

看看这个post:Angular: running function in controller when all directives are loaded

这与您的情况略有不同,但应该对您有所帮助。

您还应该阅读以下内容:https://github.com/angular/angular.js/issues/2095