【问题标题】:Add extra methods to directive form向指令表单添加额外的方法
【发布时间】:2015-09-02 15:05:01
【问题描述】:

我在 Angular 中有一个自定义表单:

<form rp-form>
  <input type="text" value="one">
  <input type="text" value="two">
  <button type="submit">submit</button>
</form>

我想使用 angular 指令添加一个方法来处理表单的提交以及输入字段的有效性:

angular.module('app', [])
    .directive('rpForm', function($compile) {
        return {
            scope: true,
            compile: function(tElement, tAttrs) {
                tElement
                    .attr({
                        name: 'testForm',
                        'ng-submit': 'mySubmit($element)'
                    })
                 return {
                     post: function(scope, element) {
                        // $compile(element[0])(scope); //causes infinite loop
                        console.log(scope);
                     }
                 };
            },
            controller: function($scope) {
                $scope.mySubmit = function(e) {
                    console.log('my submit fired');
                };
           }
    };
});

我希望能够在 postLink 函数中使用“mySubmit”方法,也希望能够在范围内看到表单指令对象“testForm”。这可以使用角度吗?

Plunker

【问题讨论】:

  • 我不知道你想做什么。您是否尝试从指令外部向表单添加提交方法 - &lt;form ng-submit="doSomething()"&gt;- 或者您是否试图让指令为您执行此操作?因为您可以只使用 ng-submit 而不必编写自己的指令。
  • @MicahWilliamson 在我正在处理的项目中,我无法更改标记,我必须在指令代码中添加 ng-submit; ng-submit 确实被添加了,但由于某种原因它不起作用。

标签: angularjs


【解决方案1】:

这是不好的做法,但可行。问题是您使用scope: true 隔离范围。删除该行。

【讨论】:

    【解决方案2】:

    compile 主要用于修改模板,即子 DOM 元素。而且这里看起来不太好,因为编译元素本身添加了一个新指令,因此应该重新编译它(它显然会导致递归,因此必须额外控制递归行为)。

    最直接的方式是rp-form 元素指令和&lt;form ng-submit="mySubmit()" ng-transclude&gt;&lt;/form&gt; 模板。

    ng-submit 指令没有真正的需要,因为它本质上是adds a listener to the element。您可以在(发布)链接中自己完成。由于您无法修改标记,因此它将是

    angular.module('app', [])
        .directive('rpForm', function($compile) {
            return {
                scope: true,
                link: function(scope, element, attrs) {
                    element.attr({
                        name: 'testForm'
                    });
                    element.on('submit', function () {
                        scope.$apply('mySubmit()');
                    });
                    console.log(scope);
                },
                controller: function($scope) {
                    $scope.mySubmit = function(e) {
                        console.log('my submit fired');
                    };
               }
        };
    });
    

    如果只在link中使用mySubmit,则在作用域上是不必要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 2020-11-16
      • 2012-01-13
      • 1970-01-01
      相关资源
      最近更新 更多