用html包裹指令元素



我想设置一个指令来加速我正在做的一些形式建设。如果我写一个这样的元素

<input type="text" name="someName" placeholder="A Placeholder" form-title="Some Name" />

最终呈现为

<div class="formKey">
    Some Name
</div>
<div>
    <input type="text" name="someName" placeholder="A Placeholder" form-title="Some Name" />
</div>

基本上它只是用一些html包装了指令所在的元素。我已经看到了angular的指令选项template改变html,和transclude保持内部html,但我找不到任何这样做。这可能吗?

是的,你的transclude是正确的。

试试这样写:

app.directive('customInput', function() {
    return {
      restrict: 'A',
      transclude: element,
      scope: { form-title: '@' },
      templateUrl: 'page.html'
    };
  });

Page.html:

<div class="formKey">
    {{form-title}}
</div>
<div ng-transclude></div>
并从你的HTML中调用它:
<input customInput type="text" name="someName" placeholder="A Placeholder" form-title="Some Name" />

基本上你可以做一些链接,但是你需要添加一个自定义指令,如下所示:

    <custom-input form-title="Some Name">
        <input type="text" name="someName" placeholder="A Placeholder"/>
    </custom-input>
然后添加一个指令代码,
    myApp.directive('customInput', function() {
      return {
        restrict: 'E',
        transclude: true,
        scope : {
            formTitle : '@'
        },
        templateUrl: 'my-wrapper.html'
      };
    });

my-wrapper.html是

<div class="formKey">
    {{formTitle}}
</div>
<div ng-transclude></div>

希望这有帮助!!

最新更新