Issue
I have a form with two submit input types. Depending on which submit is clicked I want to save the form either as draft or a correct one.
I was thinking about adding a value/property to the submit inputs, maybe ng-model attribute..
<form ng-submit="submitNew()">
<div>
Text:
<input type="text" ng-model="myForm.text" />
</div>
<div>
<input type="submit" name="correct" value="Add new" />
</div>
<div>
<input type="submit" name="draft" value="Save as draft" />
</div>
</div>
</form>
In controller I would like to add this as a boolean value ("myForm.isDraft") to data sent with POST method:
myApp.controller('myAppController', ['$scope', '$http', '$log',
function($scope, $http, $log) {
$scope.submitNew = function() {
$http({
method: 'POST',
url: '/app/submit',
data: {
text: $scope.myForm.text,
isDraft: $scope.myForm.isDraft,
}
})
};
}
]);
How does it work with inputs of submit type?
Edit - a step forward:
After changing submits to:
<div>
<input type="submit" ng-click="isDraft = false" value="Add new" />
</div>
<div>
<input type="submit" ng-click="isDraft = true" value="Save as draft" />
</div>
and adding log inside $scope.submitNew = function()
I see that $scope.isDraft is either true or false depending on which button is clicked. However, in the data sent to the back-end it is always false.
Controller now:
$scope.submitNew = function() {
$log.info("Log: isDraft: " + $scope.isDraft);
$http({
method: 'POST',
url: '/app/submit',
data: {
text: $scope.myForm.text,
isDraft: $scope.myForm.isDraft = $scope.isDraft,
}
})
};
If I change isDraft: $scope.myForm.isDraft = $scope.isDraft
to isDraft = $scope.isDraft
it's still not working properly.
Solution
Try putting it on a function like
$scope.setDraft = function(isDraft) {
$scope.isDraft = isDraft;
//try console.log() to see if the values are correct
//but if its keeps return false try adding this $scope.$apply();
}
and in your html would be like this
<div>
<input type="submit" ng-click="setDraft(false)" value="Add new" />
</div>
<div>
<input type="submit" ng-click="setDraft(true)" value="Save as draft" />
</div>
or you can use @Eric suggestion instead using ng-submit, just create new function and use on ng-click like this
$scope.submitNew = function(isDraft) {
$http({
method: 'POST',
url: '/app/submit',
data: {
text: $scope.myForm.text,
isDraft: isDraft,
}
})
};
and in the html would be like this
<form>
<div>
Text:
<input type="text" ng-model="myForm.text" />
</div>
<div>
<input type="button" ng-click="submitNew(false)" name="correct" value="Add new" />
</div>
<div>
<input type="button" ng-click="submitNew(true)" name="draft" value="Save as draft" />
</div>
</div>
</form>
Answered By - Moralde-Sama
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.