【问题标题】:How to use transclude without template in Angular directive?如何在 Angular 指令中使用不带模板的 transclude?
【发布时间】:2013-08-06 17:28:36
【问题描述】:
<button command="saveCmd">{{saveText}}</button>

命令指令没有任何模板——它是行为指令。但我需要使用transclude: true 来显示{{saveText}}

我可以创建像template: "&lt;div ng-transclude&gt;&lt;/div&gt;" 这样的虚拟模板,但我不确定按钮内的 div 是否对所有浏览器都是有效的 html。

我也可以使用属性来定义标题,例如&lt;button title="saveText"... 但我的问题是关于没有模板的 ng-transclude。可能吗?

提前致谢。

更新:

一个新的“隔离”范围scope: {} inside 指令是默认情况下不保留 {{saveText}} 的原因。

【问题讨论】:

标签: javascript angularjs angularjs-directive


【解决方案1】:

您可以在没有控制器且没有隔离范围的情况下创建指令。在链接功能中,我有时会这样做:

.directive('toggle', function ($parse) {
  return {
    /* We can't use an isolated scope in this directive, because it happens 
     * all the time that you need to put a toggle on an element that uses the scope:
     * <span toggle="boolVar" ng-class="{active: boolVar}">{{someVar}}</span>
     *
     * Transclusion can be an option to make the {{someVar}} work, 
     * but the ng-class will use the isolated scope for this directive
     * (if we'd use the isolated scope, which we don't)
     */
    link: function (scope, $element, attrs) {
      // use a $parse getter/setter, because toggle can contain a
      // complicated expression
      var getter = $parse(attrs.toggle);
      var setter = getter.assign;

      $element.on('click', function () {
        scope.$apply(function () {
          setter(scope, !getter(scope));
        });
      });
    }
  };
});

也许这个 $parse 技巧有助于您设置命令...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-09
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-01
    • 2016-09-22
    • 2013-05-14
    相关资源
    最近更新 更多