Reputation: 175
I'm using angular 1, and trying to set a variable when a form is submitted using ng-click or ng-submit. That variable then cascades and removes the form from the DOM using an ng-if. However, I run into the chrome error message "Form submission canceled because the form is not connected", and the form is not posted.
Here's a complete MWE:
<html>
<head>
<title>Something</title>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-if="status.value=='ok'">
<form action="url" method="post" target="_blank">
<button type="submit" ng-click="status.value='newwindow'">Open in new window</button>
</form>
</div>
<div>{{status}}</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
var ctrl = app.controller('myCtrl', ['$scope', function($scope) {
$scope.status = {'value':'ok'};
}]);
</script>
</body>
</html>
Whenever I completely remove the ng-* attributes, the form submits normally, but then the variable isn't updated.
Any suggestions on how to keep the form around just long enough to post it?
Upvotes: 2
Views: 2949
Reputation: 1885
<html>
<head>
<title>Something</title>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-if="status.value=='ok'">
<form action="url" method="post" ng-submit="formSubmit()" target="_blank">
<button type="submit" ng-click="status.value='newwindow'">Open in new window</button>
</form>
</div>
<div>{{status}}</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
var ctrl = app.controller('myCtrl', ['$scope', function($scope) {
$scope.status = {'value':'ok'};
$scope.formSubmit=function(){
//here you can write you business logic here
};
}]);
</script>
</body>
</html>
or you can also write:
<form action="url" method="post" target="_blank">
<button type="submit" ng-click="postData()">Open in new window</button>
</form>
in your controller:
$scope.postData=function(){
//logic will be here:
}
Upvotes: 0
Reputation: 22323
The problem in your code here is the ng-if
statement. When you click the button, the status.value
is updated immediately, causing a $digest
cycle. The $digest
cycle causes the ng-if
to be false
, which removes the entire div
(including the form) from the DOM.
One possible fix would be to use ng-show
instead of ng-if
, which just hides the element, but does not remove it from the DOM.
Another possibility would be to attach the ng-click
to a function which handles all the form submission logic, and perhaps even suppresses the default submission with event.preventDefault()
.
Upvotes: 2