我有一个包含大量Formuars的网站,我总是在提交表单之前和之后做同样的事情。所以我想写一个指令,它隐藏了必须要做的魔术。
我是下面的标记(ng-click只是为了缩短代码。在实际代码中它将隐藏在模板中):
<form class="form" name="form" ng-submit="customSubmit()">
<input ... />
<my-submit ng-click="fakeSubmit()" type="button">Submit</my-submit>
</form>
mySubmit指令应如下所示:
module.directive('MySubmit', function ($state) {
return {
restrict: 'E',
controller: function ($scope) {
$scope.fakeSubmit = function () {
// deactivate button
var result = magicThing.callSubmitFromForm();
// activate button
// throw event, that form was submitted
return false;
}
}
};
});
在指令控制器中有一行magicThing.callSubmitFromForm()
。这应该使用验证器等触发ngSubmit魔术,然后调用Method customSubmit()。我还希望得到方法customSubmit的结果,它可能是一个Callback或其他东西。
正如我上面提到的,我想写一个通用指令,所以我不知道我在这里调用的函数customSubmit()
有没有人知道如何做到这一点?
答案 0 :(得分:0)
我自己解决了这个问题。我只是覆盖ngSubmit指令并在Submit指令中使用Callback。这是代码:
module.directive('ngSubmit', function ($q) {
return {
restrict: 'A',
link: function (scope, elem, attr) {
scope.mySubmit = function (callback) {
scope.loading= true;
scope.finished= false;
$q.when(callback()).then(function () {
scope.finished= true;
}).finally(function () {
scope.loading= false;
});
};
}
};
});
module.directive('submitBtn', function ($state) {
return {
restrict: 'E',
templateUrl: 'myTemplate.html',
link: function (scope, elem, attr) {
scope.disableAfterSubmit = attr.disableAfterSubmit === 'true';
}
};
});
<form class="form" ng-submit="mySubmit(submitFkt)" ng-controller="AmnesiaPasswordCtrl">
<input ... />
</form>
<button type="submit" class="btn btn-primary" ladda="loading" ng-disabled="disable === true && finished">
Submit
</button>