【发布时间】: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”。这可以使用角度吗?
【问题讨论】:
-
我不知道你想做什么。您是否尝试从指令外部向表单添加提交方法 -
<form ng-submit="doSomething()">- 或者您是否试图让指令为您执行此操作?因为您可以只使用 ng-submit 而不必编写自己的指令。 -
@MicahWilliamson 在我正在处理的项目中,我无法更改标记,我必须在指令代码中添加 ng-submit; ng-submit 确实被添加了,但由于某种原因它不起作用。
标签: angularjs