$templateCache来自未定义的文件?其他js代码何时可以访问?(使用np自动完成)



我对angular很陌生,我正在尝试在我的应用程序中集成np自动完成(https://github.com/ng-pros/np-autocomplete)。然而,只有当我在$scope.options中传递一个html字符串作为模板时,它才能工作,而当我想从一个单独的html加载它时,它就不工作了。

我的应用程序的代码如下所示:

var eventsApp = angular.module('eventsApp',['ng-pros.directive.autocomplete'])
eventsApp.run(function($templateCache, $http) {
    $http.get('test.html', {
      cache: $templateCache
    });
   console.log($templateCache.get('test.html'))  // --> returns undefined
   setTimeout(function() {
       console.log($templateCache.get('test.html'))  // --> works fine
   }, 1000);
   //$templateCache.put('test.html', 'html string') //Would solve my issue in the controller,
   //but I would rather prefer to load it from a separate html as I'm trying above

在我的控制器中,我正在设置自动完成选项,如下所示:

controllers.createNewEventController = function ($scope) {
    $scope.options = {
        url: 'https://api.github.com/search/repositories',
        delay: 300,
        dataHolder: 'items',
        searchParam: 'q',
        itemTemplateUrl: 'test.html',  // <-- Does not work  
    };
    //other stuff...
}

然而,当np autocomplete想要使用test.html时,它似乎还没有定义(就像上面的第一个console.log中一样)。

因此,我的直觉告诉我,在将test.html加载到eventsApp.run(…)之前,可能会在控制器中访问它。然而,我不确定如何解决这个问题?

如有任何帮助,我们将不胜感激。

您的假设很可能是正确的。

$http的调用是异步的,但运行块不会等待它完成。它将继续执行,在检索和缓存模板之前,执行将到达控制器等。

一种解决方案是首先检索所有需要的模板,然后手动引导应用程序。

另一种可行的方法是推迟执行np-autocomplete指令,直到检索到模板为止。

为了防止np-autocomplete过早运行,可以使用ng-if:

<div np-autocomplete="options" ng-if="viewModel.isReady"></div>

检索到模板后,可以触发一个事件:

$http.get('test.html', {
  cache: $templateCache
}).success(function() {
  $rootScope.$broadcast('templateIsReady');
});

在控制器中监听事件并作出反应:

$scope.$on('templateIsReady', function () {
  $scope.viewModel.isReady = true;
});

如果你想的话,你可以立即停止监听,因为事件应该只触发一次:

var stopListening = $scope.$on('templateIsReady', function() {
  $scope.viewModel.isReady = true;
  stopListening();
});

最新更新