0

我对 Angular 比较陌生,我正在尝试将 np-autocomplete 集成到我的应用程序中(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...
}

但是,似乎 test.html 在 np-autocomplete 想要使用它时是未定义的(因为它也在上面的第一个 console.log 中)。

所以我的直觉告诉我,test.html 可能在加载到 eventsApp.run(...) 之前在控制器中被访问。但是我不确定如何解决这个问题?

任何帮助将不胜感激。

4

1 回答 1

1

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

$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();
});
于 2015-11-20T18:28:50.520 回答