首页 文章

在指令中自定义模板

提问于
浏览
97

我有一个使用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,如下所示:

<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 ,我想将它添加到输出中生成的 <input /> ,否则忽略它 . 我不知道如何实现这一目标 .

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

4 回答

  • 211
    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);
            }
        };
    })
    
  • 5

    试图使用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
            }
        }
    })
    
  • 38

    遗憾的是,上述答案并不奏效 . 特别是,编译阶段无权访问范围,因此您无法基于动态属性自定义字段 . 使用链接阶段似乎提供了最大的灵活性(就异步创建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));
          }
        }
      }
    })
    

    我创建了a gist,其中包含更完整的代码和writeup方法 .

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

相关问题