【问题标题】:Customizing the template within a Directive在指令中自定义模板
【发布时间】:2012-05-24 15:32:02
【问题描述】:

我有一个使用 Bootstrap 标记的表单,如下所示:

<form class="form-horizontal">
  <fieldset>
    <legend>Legend text</legend>
    <div class="control-group">
      <label class="control-label" for="nameInput">Name</label>
      <div class="controls">
        <input type="text" class="input-xlarge" id="nameInput">
        <p class="help-block">Supporting help text</p>
      </div>
    </div>
  </fieldset>
</form>

那里有很多样板代码,我想简化为一个新指令 - 表单输入,如下所示:

<form-input label="Name" form-id="nameInput"></form-input>

生成:

   <div class="control-group">
      <label class="control-label" for="nameInput">Name</label>
      <div class="controls">
        <input type="text" class="input-xlarge" id="nameInput">
      </div>
    </div>

我通过一个简单的模板完成了这么多工作。

angular.module('formComponents', [])
    .directive('formInput', function() {
        return {
            restrict: 'E',
            scope: {
                label: 'bind',
                formId: 'bind'
            },
            template:   '<div class="control-group">' +
                            '<label class="control-label" for="{{formId}}">{{label}}</label>' +
                            '<div class="controls">' +
                                '<input type="text" class="input-xlarge" id="{{formId}}" name="{{formId}}">' +
                            '</div>' +
                        '</div>'

        }
    })

但是,当我开始添加更高级的功能时,我遇到了困难。

如何在模板中支持默认值?

我想在我的指令中将“type”参数作为可选属性公开,例如:

<form-input label="Password" form-id="password" type="password"/></form-input>
<form-input label="Email address" form-id="emailAddress" type="email" /></form-input>

但是,如果没有指定任何内容,我想默认为"text"。我该如何支持?

如何根据属性的有无自定义模板?

我还希望能够支持“必需”属性(如果存在)。 例如:

<form-input label="Email address" form-id="emailAddress" type="email" required/></form-input>

如果指令中存在required,我想将其添加到输出中生成的&lt;input /&gt;,否则忽略它。我不确定如何实现这一点。

我怀疑这些要求可能已经超出了简单的模板,并且必须开始使用预编译阶段,但我不知道从哪里开始。

【问题讨论】:

  • 我是唯一一个在房间里看到大象的人吗:) --> 如果type 是通过绑定动态设置的,例如。 type="{{ $ctrl.myForm.myField.type}}" ?我检查了以下所有方法,但找不到任何适用于这种情况的解决方案。看起来模板函数会看到属性的 literal values,例如。 tAttr['type'] == '{{ $ctrl.myForm.myField.type }}' 而不是 tAttr['type'] == 'password'。我很困惑。

标签: javascript angularjs


【解决方案1】:
angular.module('formComponents', [])
  .directive('formInput', function() {
    return {
        restrict: 'E',
        compile: function(element, attrs) {
            var type = attrs.type || 'text';
            var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
            var htmlText = '<div class="control-group">' +
                '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                    '<div class="controls">' +
                    '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                    '</div>' +
                '</div>';
            element.replaceWith(htmlText);
        }
    };
})

【讨论】:

  • 这有点晚了,但是如果在htmlText 中添加了ng-click,唯一的修改是用element.replaceWith($compile(htmlText)) 替换element.replaceWith(htmlText) 吗?
  • @Misko,您提到要摆脱范围。为什么?我有一个指令在与隔离范围一起使用时无法编译。
  • 如果htmlText 包含 ng-transclude 指令,这将不起作用
  • 不幸的是,我发现表单验证似乎不适用于此,插入输入上的$error 标志永远不会设置。我必须在指令的链接属性中执行此操作:$compile(htmlText)(scope,function(_el){ element.replaceWith(_el); });,以便表单的控制器识别其新形成的存在并将其包含在验证中。我无法让它在指令的编译属性中工作。
  • 好的,现在是 2015 年,我很确定在脚本中手动生成标记存在严重错误。
【解决方案2】:

尝试使用Misko提出的解决方案,但在我的情况下,一些需要合并到我的模板html中的属性本身就是指令。

不幸的是,并非生成的模板引用的所有指令都能正常工作。我没有足够的时间深入研究角度代码并找出根本原因,但找到了一种解决方法,这可能会有所帮助。

解决方案是将创建模板 html 的代码从编译移动到模板函数。基于上述代码的示例:

    angular.module('formComponents', [])
  .directive('formInput', function() {
    return {
        restrict: 'E',
        template: function(element, attrs) {
           var type = attrs.type || 'text';
            var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
            var htmlText = '<div class="control-group">' +
                '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                    '<div class="controls">' +
                    '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                    '</div>' +
                '</div>';
             return htmlText;
        }
        compile: function(element, attrs)
        {
           //do whatever else is necessary
        }
    }
})

【讨论】:

  • 这解决了我在模板中嵌入 ng-click 的问题
  • 谢谢,这对我也有用。想要包装一个指令来应用一些默认属性。
  • 谢谢,我什至不知道模板接受了函数!
  • 这不是一种解决方法。这是对OP的正确答案。根据元素的属性有条件地制作模板是指令/组件模板函数的确切目的。您不应该为此使用 compile 。 Angular 团队非常鼓励这种编码风格(不使用 compile 函数)。
  • 这应该是正确的答案,即使我不知道模板有一个功能:)
【解决方案3】:

不幸的是,上述答案并不完全奏效。特别是编译阶段无法访问范围,因此您无法根据动态属性自定义字段。使用链接阶段似乎提供了最大的灵活性(在异步创建 dom 等方面)。以下方法解决了:

<!-- Usage: -->
<form>
  <form-field ng-model="formModel[field.attr]" field="field" ng-repeat="field in fields">
</form>
// directive
angular.module('app')
.directive('formField', function($compile, $parse) {
  return { 
    restrict: 'E', 
    compile: function(element, attrs) {
      var fieldGetter = $parse(attrs.field);

      return function (scope, element, attrs) {
        var template, field, id;
        field = fieldGetter(scope);
        template = '..your dom structure here...'
        element.replaceWith($compile(template)(scope));
      }
    }
  }
})

我用更完整的代码和writeup 的方法创建了a gist

【讨论】:

  • 不错的方法。不幸的是,与 ngTransclude 一起使用时出现以下错误:Error: [ngTransclude:orphan] Illegal use of ngTransclude directive in the template! No parent directive that requires a transclusion found.
  • 为什么不使用带有 'field: "="' 的隔离范围?
  • 非常好,谢谢!不幸的是,你的书面方法是离线的:(
  • 要点和文章都是死链接。
【解决方案4】:

这是我最终使用的。

我对 AngularJS 很陌生,所以很想看到更好/替代的解决方案。

angular.module('formComponents', [])
    .directive('formInput', function() {
        return {
            restrict: 'E',
            scope: {},
            link: function(scope, element, attrs)
            {
                var type = attrs.type || 'text';
                var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
                var htmlText = '<div class="control-group">' +
                    '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                        '<div class="controls">' +
                        '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                        '</div>' +
                    '</div>';
                element.html(htmlText);
            }
        }
    })

示例用法:

<form-input label="Application Name" form-id="appName" required/></form-input>
<form-input type="email" label="Email address" form-id="emailAddress" required/></form-input>
<form-input type="password" label="Password" form-id="password" /></form-input>

【讨论】:

  • 更好的解决方案是:(1)使用编译函数而不是链接函数并在那里进行替换。该模板不适用于您的情况,因为您想对其进行自定义。 (2)摆脱范围:
  • @MiskoHevery 感谢您的反馈 - 您是否介意在此处解释为什么编译功能优于链接功能?
  • 我认为这就是答案,来自docs.angularjs.org/guide/directive:“出于性能原因,任何可以在指令实例之间共享的操作[例如,转换模板 DOM] 都应该移至编译函数。”
  • @Marty 您仍然能够将您的自定义输入之一绑定到模型吗? (即&lt;form-input ng-model="appName" label="Application Name" form-id="appName" required/&gt;&lt;/form-input&gt;
  • @MartyPitt 来自 O'Reilly 的“AngularJS”一书中:“所以我们得到了处理模板转换的 compile 阶段和处理修改模板的 link 阶段视图中的数据。按照这些思路,指令中的compilelink 函数之间的主要区别在于compile 函数处理模板本身的转换,而link 函数处理模型之间的动态连接并查看。正是在第二阶段,作用域被附加到编译的link 函数,并且指令通过数据绑定变为live
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-28
  • 1970-01-01
  • 2019-05-22
  • 2014-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多