动态更改Angular指令中的html元素

时间:2015-12-12 01:46:43

标签: javascript angularjs

让我们说这个指令有一个简单的模板:

<section class="card {{width}} recipe-list-card">
  <div class="card-top">
    <h3>{{headerText}}</h3>
  </div>
  <div class="card-bottom">
    <div ng-transclude></div>
  </div>
</section>

在某些情况下,我想使用h2,而在其他情况下使用h3。有没有一种使用指令更改元素的好方法?

这是我在指令中的内容:

module.exports = function(app) {

      app.directive('cardDirective', function() {
        return {
          restrict: 'AC',
          replace: true,
          transclude: true,
          templateUrl: '/templates/card_template.html',
          scope: {
            header: '=',
            headerText: '@',
            width: '@' //two columns, three columns, etc
          }
        }
      })
    }

我想将标题变量分配给h2,h3等。到目前为止,我只能获得转义的html(在浏览器中呈现的实际标记类似于<h2>

4 个答案:

答案 0 :(得分:3)

您可以为标题标记创建一个指令,如下所示:

angular.module('myApp')
    .directive('myHeading', myHeading);

function myHeading() {
    return {
        transclude: true,
        template: function(tElement, tAttrs) {
            var level = Number(tAttrs.level);
            if (level < 1 || level > 6) level = 1; // default
            return '<h' + level + '><ng-transclude></ng-transclude></h' + level + '>';
        }
    };
}

然后你可以在你的模板中使用它:

<my-heading level="2">{{headerText}}</my-heading>

答案 1 :(得分:2)

您可以按照以下代码执行此操作

按如下方式更改HTML:

<section class="card {{width}} recipe-list-card">
  <div class="card-top">
    <h3 ng-show="h3">{{headerText}}</h3>
    <h2 ng-show="h2">{{headerText}}</h2>
  </div>
  <div ng-click="updateh2h3()">Check h2h3 changes</div>
  <div class="card-bottom">
    <div ng-transclude></div>
  </div>
</section>

并按如下方式修改控制器: module.exports = function(app){

  app.directive('cardDirective', function() {
    return {
      restrict: 'AC',
      replace: true,
      transclude: true,
      templateUrl: '/templates/card_template.html',
      scope: {
        header: '=',
        headerText: '@',
        width: '@' //two columns, three columns, etc
      },
      controller: function($scope) {
       $scope.h2 = false;
       $scope.h3 = true;
       $scope.updateh2h3 = function(){
        if($scope.h2){
         $scope.h2 = false;
         $scope.h3 = true;
        } else {
         $scope.h2 = true;
         $scope.h3 = false;
        }
       }
      }
    }
  })
}

答案 2 :(得分:1)

您只需向指令添加属性,然后使用ng-switch设置卡所需的标题。看看我做过的演示。

<div class="card">
  <div class="card--Title" ng-switch on="headline">
      <h1 ng-switch-when="h1">{{::headerText}}</h1>
      <h2 ng-switch-when="h2">{{::headerText}}</h2>
      <span ng-switch-default>{{::headerText}}</span>
  </div>
</div>

http://embed.plnkr.co/simYTj/

答案 3 :(得分:1)

我认为你正在以错误的方式看待这个问题。您可以只为h2和h3定义两个类,而不是切换标签,然后可以使用ng-class进行切换。动态编译标签和操作dom是非常昂贵的操作。