为什么模板工作和templateUrl不在我的路由中解析加载指令?

时间:2015-10-05 14:49:37

标签: angularjs

My Angular应用程序需要在加载控制器之前解析数据。我正在使用tasseKATT提供的答案:

Apply loading spinner during ui-router resolve

虽然我很好奇为什么我可以使用“模板”而不是“templateUrl”。

使用:

app.directive('resolveLoader', function($rootScope, $timeout) {
  return {
    restrict: 'E',
    replace: true,
    template: '<div class="alert alert-success ng-hide"><strong>Welcome!</strong> Content is loading, please hold.</div>',
    link: function(scope, element) {...

不起作用:

app.directive('resolveLoader', function($rootScope, $timeout) {
      return {
        restrict: 'E',
        replace: true,
        templateUrl: 'loadingView.html',
        link: function(scope, element) {...

请参阅下面修改过的Plunker(无效):

http://plnkr.co/edit/cpLDciUsXvIBL6fzAzWj?p=preview

2 个答案:

答案 0 :(得分:1)

如原始答案的评论中所述,这是一个时间问题,使用$timeout时您不需要templateUrl

所以这个:

link: function(scope, element) {

  $rootScope.$on('$routeChangeStart', function(event, currentRoute, previousRoute) {
    if (previousRoute) return;

    $timeout(function() {
      element.removeClass('ng-hide');
    });
  });

  $rootScope.$on('$routeChangeSuccess', function() {
    element.addClass('ng-hide');
  });
}

将更改为:

link: function(scope, element) {

  element.removeClass('ng-hide');

  var unregister = $rootScope.$on('$routeChangeSuccess', function() {
    element.addClass('ng-hide');
    unregister();
  });
}

以下是使用templateUrl的固定解决方案的插件(来自原始答案的评论):http://plnkr.co/edit/31qu9xcZCCEzSfHn5YyN?p=preview

答案 1 :(得分:1)

正如我在评论中所说,你必须在第一个指令中用template替换templateUrl,然后它就像这样plunker

    app.directive('resolveLoader', function($rootScope, $timeout) {
      return {
        restrict: 'E',
        replace: true,
        // wrong
        //templateUrl: '<div class="alert alert-success ng-hide">
        // should be
        template: '<div class="alert alert-success ng-hide"><strong>Welcome!</strong> Content is loading, please hold.</div>',
        link: function(scope, element) {...

然后没有时间问题,至少在我的Chrome浏览器中。