-->

AngularJS负荷标签内容动态地指令(AngularJS load tabbed content

2019-10-19 05:50发布

我在我的web应用程序选项卡式navigtion看起来像这样

现在,我希望每个用户点击导航点的一次更改指令。 我的想法是与第一模板来初始化页面。

$scope.currentDirective = $compile('<div order-Sale></div>');

然后,当用户点击一个标签,我想改变,在一个新的指令重新编译的内容。 但出于某种原因,这是行不通的。 你如何才能归档此动态内容加载继续吗? 我真的希望只加载在必要需要的内容,而不只是为了显示或隐藏。 我想用指令是去正确的方式,但我是一个,但停留在执行......有人任何指针? (我不希望使用任何的jQuery)

我试过[编辑]:

controller.js

    app.controller('pageController',['$scope','$compile', function($scope, $compile){

      var templates = ['<div first-template></div>','<div second-template></div>'];

      $scope.currentTemplate = $compile(templates[0]);

      $scope.changeTemplate = function(id) {

        $scope.currentTemplate = $compile(templates[id]);

      };

  }]);

HTML

<div ng-controller="pageController">
    <li>
        <a ng-click="changeTemplate('1')">Change Template</a>
    </li>
    {{currentTemplate}}
</div>

Answer 1:

UPDATE

  • $编译回报逻辑函数不是一个值 ,你不能只是把它绑定到与插补模板。
  • 您应该使用ngBindHtml而不是常规绑定( ngBind{{ }}
  • ngBindHtml并编译,链接,看所有外的开箱。
  • 随着NG绑定,HTML不安全取出,我怎么注入HTML?

这里是一个plunker

  app.controller('pageController',['$scope','$compile','$sce', function($scope, $compile, $sce){
    var templates = ['<div>first-template</div>','<div>second-template</div>'];
    $scope.currentTemplate = $sce.trustAsHtml(templates[0]);
    $scope.changeTemplate = function(id) {
      $scope.currentTemplate = $sce.trustAsHtml(templates[id]);
    };
  }]);

标记:

  <div ng-controller="pageController">
    <button ng-click="changeTemplate('1')">Change Template</button>
    <div ng-bind-html="currentTemplate"></div>
  </div>

对于更强大的动态内容加载你有两个很好的选择:

  • ngRoute从角队。
  • UI路由器从角UI团队。

如果你想改变和重新编译的内容,以及这正是ng-view / ui-view指令已经为你做。

为什么不直接使用一个指令:

  • 你可能需要加载为每个标签不同的模板(HTML部分)。
  • 你可能需要根据标签(反之亦然)更改URL
  • 你可能需要实例为每个标签不同的控制器。
  • ngRouteui-router来用自己的指令。
  • 你可以实现自己的路线模块,但如果你想这不仅仅是一个指令的详细。


文章来源: AngularJS load tabbed content directive dynamicly