所以我有一个指令接受一个动态加载正确模板的模板名称。 它看起来像这样:
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>
当状态改变开始时,并在 $ rootScope 上设置 loaderTemplate ,如下所示:
function run($rootScope, pkSplashService) {
$rootScope.$on('$stateChangeStart', function (event, toState) {
$rootScope.loaderTemplate = pkSplashService.getTemplate(toState.name);
console.log($rootScope.loaderTemplate);
});
};
我已将控制台日志放在 $ stateChangeStart 方法上,我可以看到交换状态时模板名称确实发生了变化,但加载器只会使用首次加载的模板。 有谁知道我怎么能改变它?
答案 0 :(得分: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';
});