简体   繁体   English

带有Angular 1.5指令的动态模板URL

[英]Dynamic template URL with Angular 1.5 directive

I am wanting to change my navbar template on a route change. 我想在路线更改时更改我的导航栏模板。

I have come up with two solutions, but I am not 100% satisfied with either. 我想出了两种解决方案,但我都不是100%满意。

1) I can define an ng-include outside of my view. 1)我可以在视图之外定义ng-include。

angular.module('automatclubApp')
  .directive('navbar', function (PartialsPath) {
    return {
      restrict: 'E',
      controller: 'NavbarCtrl',
      controllerAs: 'navCtrl'
    };
  })
  .controller('NavbarCtrl', function(PartialsPath,  $scope, $location) {
    $scope.$on('$locationChangeSuccess', function(/* EDIT: remove params for jshint */) {
        var path = $location.path();
        //EDIT: cope with other path
        $scope.templateUrl = (path==='/') ? '../scripts/directives/partials/navbar.html' : '../scripts/directives/partials/navbar_lobby.html';
    });
  });

And then include this in my index: 然后将其包含在我的索引中:

<body>
    <div ng-controller='NavbarCtrl'>
      <div ng-include='templateUrl'></div>
    </div>
   <div ng-view=""></div>
</body>

2) In my views/main.html file, I can include an ng-include like this: 2)在我的views / main.html文件中,我可以这样添加ng-include:

  <ng-include src="'../scripts/directives/partials/navbar.html'"></ng-include>

Ideally, I would love to have a directive declaration in my ng-view for a bit cleaner code. 理想情况下,我希望在ng-view中有一个指令声明,以获得更简洁的代码。 Any suggestions? 有什么建议么? It says my navbar controller is undefined when I can it in ng-view, which is why it seems solution one isn't working like I intended. 它说我在ng-view中可以使用时,我的navbar控制器是未定义的,这就是为什么似乎解决方案一没有按我预期的那样工作的原因。

I have a solution I am happy with. 我有一个满意的解决方案。

Directive: 指示:

angular.module('automatclubApp')
  .controller('NavbarCtrl', function($scope, $location) {
    // $scope.myTemplate = '<span class="custom-tpl" style="color: white"> my template </span>';
    $scope.getTemplateUrl = function() {
      var path = $location.path();
      return path ==='/' ? '../scripts/directives/partials/navbar.html' : '../scripts/directives/partials/navbar_lobby.html';
    };
  })
  .directive('navbar', function ($compile) {
    return {
      restrict: 'E',
      template: '<ng-include src="getTemplateUrl()">'
    };
  });

Which can be invoked in the view like this: 可以在视图中这样调用:

<div ng-controller='NavbarCtrl'>
  <navbar></navbar>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM