【问题标题】:AngularJS load tabbed content directive dynamiclyAngularJS 动态加载选项卡式内容指令
【发布时间】:2014-01-16 12:58:00
【问题描述】:

我的 web 应用中有一个选项卡式导航,看起来像这样

现在我想在用户每次单击导航点之一时更改指令。我的想法是用第一个模板初始化页面。

$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>

【问题讨论】:

  • 显示您的代码并显示您尝试过的内容。
  • 添加了我测试过的内容
  • 我更新了我的答案。提问时请避开for some reason this is not working,提供代码示例,方便转载。它将为每个人节省大量时间和误解。让代码解释为什么它不起作用。

标签: angularjs dynamic angularjs-directive


【解决方案1】:

更新

这是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>

要获得更强大的动态内容加载,您有两个不错的选择:

如果您想再次更改和编译内容,那正是 ng-view/ ui-view 指令已经为您做的事情。

为什么不直接使用指令:

  • 您可能需要为每个选项卡加载不同的模板(html 部分)。
  • 您可能需要根据标签更改网址(反之亦然)
  • 您可能需要为每个选项卡实例化不同的控制器。
  • ngRouteui-router 带有自己的指令。
  • 您可以根据需要实现自己的路由模块,但这不仅仅是一个指令。

【讨论】:

  • 我只想将指令更新为另一个指令或更改指令的模板。不要改变整个视图。
猜你喜欢
  • 2013-12-18
  • 2015-11-26
  • 2021-05-09
  • 1970-01-01
  • 1970-01-01
  • 2016-09-28
  • 1970-01-01
  • 2021-01-29
  • 2018-04-20
相关资源
最近更新 更多