2017-07-18 91 views
0

所以我有一个指令,接受模板名称动态加载正确的模板。 它看起来像这样:Angularjs加载屏幕与动态模板

angular.module('widget.directives').directive('pkSplash', directive); 

function directive() { 
    return { 
     restrict: 'A', 
     controller: 'PkSplashController', 
     controllerAs: 'controller', 
     bindToController: true, 
     template: '<div ng-include="contentUrl"></div>', 
     link: lnkFn 
    }; 

    function lnkFn(scope, element, attrs, controller) { 
     scope.contentUrl = 'app/directives/pkSplash-' + attrs.pkSplash + '.html'; 
     attrs.$observe('template', function (template) { 
      scope.contentUrl = 'app/directives/pkSplash-' + template + '.html'; 
     }); 
     scope.$watch(controller.loading, function (loading) { 
      controller.loaded = !loading; 
     }); 
    }; 
}; 

的指令实际上坐在的index.html页面这样的:

<div pk-splash="{{ loaderTemplate }}" ng-if="loaderTemplate"></div> 

loaderTemplate是在$ rootScope设置时,状态变化开始,像这样:

function run($rootScope, pkSplashService) { 
    $rootScope.$on('$stateChangeStart', function (event, toState) { 
     $rootScope.loaderTemplate = pkSplashService.getTemplate(toState.name); 
     console.log($rootScope.loaderTemplate); 
    }); 
}; 

我已经把控制台日志放在$ stateChangeStart方法中,我可以看到当交换表明模板名称确实发生了变化,但加载器只会使用首次加载的模板。 有谁知道我怎么能改变它?

回答

1

在这一部分,它看起来就像你正在观察所谓的“模板”的属性,但是你是不是传递一个:

attrs.$observe('template', function (template) { 
     scope.contentUrl = 'app/directives/pkSplash-' + template + '.html'; 
    }); 

在这种情况下,你需要使用它是这样的:

<div pk-splash template="{{ loaderTemplate }}" ng-if="loaderTemplate"></div> 

另一种选择将是观察的pkSplash属性改为:

attrs.$observe('pkSplash', function (template) { 
    scope.contentUrl = 'app/directives/pkSplash-' + template + '.html'; 
});