【问题标题】:Add class to transcluded element向嵌入元素添加类
【发布时间】:2015-04-22 20:17:02
【问题描述】:

假设我有一个如下所示的指令:

<input class="icon-input" type="text">

我想这样结束:

<div class="col-xs-12">
  <i ng-class="icon"></i>
  <input class="icon-input" type="text" class="form-control">
</div>

(上面的重要部分是class="form-control"。)

我的指令目前看起来像这样:

'use strict';

class IconInput {
  constructor() {
    this.restrict = 'C';
    this.replace = true;
    this.transclude = 'element';
    this.templateUrl = 'app/form-fields/icon-input/icon-input.html';
    this.scope = { icon: '@' }
  }
}

export default IconInput;

如何将class="form-control" 添加到我的嵌入的input 元素中?

【问题讨论】:

  • 您应该只嵌入输入,并从外部传递类,输入定义。
  • “仅包含输入”是什么意思?我以为这就是我正在做的事情。
  • 按照您的方式,模板的所有内容都被替换了。如果您使用 ng-transclude 作为模板的一部分,它将替换原始输入 + 模板的其余部分。
  • 你可以在这里看到类似的东西:stackoverflow.com/questions/22931740/…

标签: angularjs


【解决方案1】:

我最终自己弄清楚了。

'use strict';

class IconInput {
  constructor() {
    this.restrict = 'C';
    this.transclude = true;
    this.scope = { icon: '@' };

    this.compile = (element, attrs, transclude) => {
      return $scope => {
        transclude($scope, clone => {
          element.append(clone)
            .wrap('<div class="col-xs-12"></div>')
            .before(`<i class="fa ${$scope.icon}"></i>`)
            .addClass('form-control');
        });
      };
    };
  }
}

export default IconInput;

【讨论】:

    猜你喜欢
    • 2014-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 2018-06-12
    • 2011-06-17
    • 1970-01-01
    相关资源
    最近更新 更多