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

时间:2016-09-13 06:25:17

标签: javascript angularjs yeoman-generator-angular

我想在路线更改时更改导航栏模板。

我已经提出了两个解决方案,但我对这两个方案都不是100%满意。

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';
    });
  });

然后将其包含在我的索引中:

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

2)在我的views / main.html文件中,我可以包含这样的ng-include:

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

理想情况下,我希望在我的ng-view中有一个指令声明,以获得更清晰的代码。有什么建议?它说我的导航栏控制器在ng-view中是不确定的,这就是为什么解决方案似乎没有像我想的那样工作。

1 个答案:

答案 0 :(得分:0)

我有一个我很满意的解决方案。

指令:

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()">'
    };
  });

可以在视图中调用,如下所示:

<div ng-controller='NavbarCtrl'>
  <navbar></navbar>
</div>
相关问题