在指令中自定义模板

Mar*_*itt 98 javascript angularjs

我有一个使用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>
Run Code Online (Sandbox Code Playgroud)

那里有很多样板代码,我想减少到一个新的指令 - form-input,如下所示:

<form-input label="Name" form-id="nameInput"></form-input>
Run Code Online (Sandbox Code Playgroud)

产生:

   <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>
Run Code Online (Sandbox Code Playgroud)

我通过一个简单的模板工作了很多.

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

        }
    })
Run Code Online (Sandbox Code Playgroud)

然而,当我加入更多高级功能时,我就会陷入困境.

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

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

<form-input label="Password" form-id="password" type="password"/></form-input>
<form-input label="Email address" form-id="emailAddress" type="email" /></form-input>
Run Code Online (Sandbox Code Playgroud)

但是,如果没有指定任何内容,我想默认为"text".我怎么能支持这个?

如何根据属性的存在/不存在自定义模板?

我也希望能够支持"必需"属性,如果它存在的话.例如:

<form-input label="Email address" form-id="emailAddress" type="email" required/></form-input>
Run Code Online (Sandbox Code Playgroud)

如果required指令中存在,我想将它添加到<input />输出中生成的,否则忽略它.我不知道如何实现这一目标.

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

Mis*_*ery 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);
        }
    };
})
Run Code Online (Sandbox Code Playgroud)

  • 这有点晚了,但是如果在`htmlText`中你在某处添加了一个`ng-click`,那么唯一的修改就是用`element.replaceWith($ compile(htmlText))替换`element.replaceWith(htmlText)`. ? (6认同)
  • 好的,它是2015年的,我很确定在脚本**中手动生成标记有一些非常错误**. (5认同)
  • 不幸的是我发现表单验证似乎不适用于此,插入的输入上的`$ error`标志永远不会被设置.我必须在一个指令的link属性中执行此操作:`$ compile(htmlText)(scope,function(_el){element.replaceWith(_el);});`以便表单的控制器识别其新形成的存在并包含它在验证中.我无法让它在指令的编译属性中工作. (3认同)

小智 38

试图使用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
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,我甚至不知道模板接受了一个功能! (2认同)
  • 这不是一种解决方法.这是OP的正确答案.根据元素的属性有条件地制作模板是指令/组件模板函数的确切目的.你不应该使用编译.Angular团队非常鼓励这种编码风格(不使用编译功能). (2认同)

Joe*_*oeS 5

遗憾的是,上述答案并不奏效.特别是,编译阶段无权访问范围,因此您无法基于动态属性自定义字段.使用链接阶段似乎提供了最大的灵活性(就异步创建dom等而言)以下方法解决了:

<!-- Usage: -->
<form>
  <form-field ng-model="formModel[field.attr]" field="field" ng-repeat="field in fields">
</form>
Run Code Online (Sandbox Code Playgroud)
// 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));
      }
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

我已经创建了一个包含更完整代码和该方法的写法要点.