带有angularJS的表单上的空操作属性

Ale*_*era 5 html forms angularjs

我试图在AngularJS应用程序中以正常方式提交表单但我遇到了一个问题:似乎我必须指定action属性.

根据HTML规范(http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#form-submission-algorithm):

如果action是空字符串,则让action成为表单文档的文档地址.

但是,如果未填充action属性,AngularJS将拒绝提交表单.我找到的解决方法是使用action ="#",但这不是一个可接受的解决方案,因为我可能会使用哈希,我不希望它被重写.

有没有人遇到过这个问题?

编辑:我不想对这个表单使用angular,我只是想以"旧"的方式提交它

rob*_*mes 6

我创建了一个小指令来解决这个问题:

.directive('form', ['$location', function($location) {
    return {
        restrict:'E',
        priority: 999,
        compile: function() {
            return {
                pre: function(scope, element, attrs){
                    if (attrs.noaction === '') return;
                    if (attrs.action === undefined || attrs.action === ''){
                        attrs.action = $location.absUrl();
                    }
                }
            }
        }
    }
}]);
Run Code Online (Sandbox Code Playgroud)

似乎对我有好处.它查找动作为空的表单,并将其设置为当前URL.

实际上,它没有设置动作 - 它设置了attr值,所以实际的form指令认为它有一个.

@Reimund 更新很好 - 我实际上也必须这样做.

新更新 - 我添加了一个noaction向表单元素添加属性的选项; 这使您可以返回"正常"角度情况.否则,如果使用ajax,此指令将提交两次表单.


Aur*_*ret 4

在库中,您可以看到 Angular 监听表单事件submit而不执行任何操作:https://github.com/angular/angular.js/blob/b9fa5c5a6781f4e1ec337f27d55c69db491a6555/src/ng/directive/form.js#L331

\n\n

您可以评论这一行,它有效,但我反对编辑库的代码。

\n\n

几行之后,您可以看到 Angular 正在侦听该事件$destroy,从而可以删除对此事件的操作。

\n\n

因此,为了避免修改 Angular,您可以只触发表单的此事件:

\n\n
angular.element(document).ready(function(){\n    angular.element(document.querySelector("#loginForm")).triggerHandler("$destroy")\xe2\x80\x8c\xe2\x80\x8b; \n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

上面几行描述了这种行为的原因:

\n\n
\n

我们不能使用 jq 事件,因为如果表单在提交期间被破坏,则不会阻止默认操作。

\n
\n\n

相关问题是:https://github.com/angular/angular.js/issues/1238

\n