How to submit form after validation in angularjs? - javascript

var app = angular.module('formExample', []);
app.controller('FormCtrl', function ($scope, $http) {
$scope.data = {};
$scope.submitForm = function() {
formData = $scope.regform;
console.log("posting data....");
$http({ url: '/',data: $scope.regform, method: 'post' }).success();
console.log(formData);
};
$scope.reset = function(form) {
if (form) {
form.$setPristine();
form.$setUntouched();
}
$scope.user = angular.copy($scope.data);
};
$scope.reset();
});
This is my JavaScript code. It submit form along with validation. I need only submit form after validation done. And the reset button not working properly.
Click here plnkr example

you can rather create a directive for this purpose
code below answer is copied from here, (copy pasted as link only answers are not allowed)...
var app = angular.module('plunker', []);
var ValidSubmit = ['$parse', function ($parse) {
return {
compile: function compile(tElement, tAttrs, transclude) {
return {
post: function postLink(scope, element, iAttrs, controller) {
var form = element.controller('form');
form.$submitted = false;
var fn = $parse(iAttrs.validSubmit);
element.on('submit', function(event) {
scope.$apply(function() {
element.addClass('ng-submitted');
form.$submitted = true;
if(form.$valid) {
fn(scope, {$event:event});
}
});
});
}
}
}
}
}]
app.directive('validSubmit', ValidSubmit);
and then in html
<form class="form-horizontal" role="form" name="form" novalidate valid-submit="connect()">
<div class="form-group">
<div class="input-group col col-sm-11 col-sm-offset-1">
<span class="input-group-addon input-large"><i class="glyphicon glyphicon-envelope"></i></span>
<input class="input-large form-control" type="email" id="email" placeholder="Email" name="email" ng-model="email" required="required">
</div>
<p class="col-sm-offset-3 help-block error" ng-show="form.$submitted && form.email.$error.required">please enter your email</p>
<p class="col-sm-offset-3 help-block error" ng-show="form.$submitted && form.email.$error.email">please enter a valid email</p>
</div>
</form>
The PLUNKER LINK to check this

Related

AngularJS 1.6.8: Unable to submit form and display success message

I have a simple query submission form with name, email and query fields and a component with a controller function having the submit function to submit the form.
I am using ng-submit directive in the <form></form> tag to submit the user input and display a success message on submission.
below is the code for the respective files.
contact.html
<div ngController="contactController as vm">
<div class="heading text-center">
<h1>Contact Us</h1>
</div>
<div>
<form class="needs-validation" id="contactForm" novalidate method="post" name="vm.contactForm" ng-submit="saveform()">
<div class="form-group row">
<label for="validationTooltip01" class="col-sm-2 col-form-label">Name</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipName" placeholder="Name" ng-model="vm.name" required>
<div class="invalid-tooltip">
Please enter your full name.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltipEmail" class="col-sm-2 col-form-label">Email</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="validationTooltipUsernamePrepend">#</span>
</div>
<input type="email" class="form-control" id="validationTooltipEmail" placeholder="Email"
aria-describedby="validationTooltipUsernamePrepend" ng-model="vm.email" required>
<div class="invalid-tooltip">
Please choose a valid email.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltip03" class="col-sm-2 col-form-label">Query</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipQuery" ng-model="vm.query" placeholder="Query" required>
<div class="invalid-tooltip">
Please write your Query.
</div>
</div>
</div>
<div class="btn-group offset-md-5">
<button class="btn btn-primary" type="submit">Submit</button>
<button class="btn btn-default" type="button" id="homebtn" ng-click="navigate ('home')">Home</button>
</div>
</form>
<span data-ng-bind="Message" ng-hide="hideMessage" class="sucessMsg"></span>
</div>
</div>
contact.component.js
angular.module('myApp')
.component('contactComponent', {
restrict: 'E',
$scope:{},
templateUrl:'contact/contact.html',
controller: contactController,
controllerAs: 'vm',
factory:'userService',
$rootscope:{}
});
function contactController($scope, $state,userService,$rootScope) {
var vm = this;
$scope.navigate = function(home){
$state.go(home)
};
$scope.saveform = function(){
$scope.name= vm.name;
$scope.email= vm.email;
$scope.query= vm.email;
$scope.hideMessage = false;
$scope.Message = "Your query has been successfully submitted."
};
$scope.user = userService;
};
//localStorage code
function userService($rootScope) {
var service = {
model: {
name: '',
email: '',
query:''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (sessionStorage.restorestate == "true") {
$rootScope.$broadcast('restorestate'); //let everything know we need to restore state
sessionStorage.restorestate = false;
}
});
//let everthing know that we need to save state now.
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
};
UPDATE: On Submit, When I check the response in network tab in dev tools, I do not see the submitted values. All I see is the markup.
In your template, the name of the method is saveform:
ng-submit="saveform()"
But in your controller, it's save:
$scope.save = function() { ... }
Rename it to saveform:
$scope.saveform = function() { ... }

TypeError: Attempted to assign to readonly property - when typing in a text field

I recently updated my Angular from 1.5.x to 1.6.4 and now, when I go to a form, I get the below error message whenever I try to type something up in the form/textbox:
TypeError: Attempted to assign to readonly property.
This is my controller:
mainApp.controller('newPostController', ['$scope', '$http', function($scope, $http){
$scope.post = '';
$scope.postCreated = false;
$scope.makeNewPost = function() {
$http.post('/api/post', {
title: $scope.post.title,
})
.then(function(res){
$scope.postCreated = true;
//extra code not related to the form itself...
};
}]);
My HTML looks like this:
<form ng-submit="makeNewPost()">
<div class="form-group">
<label for="title" class="control-label">Title</label>
<input type="text" autocomplete="off" class="form-control" ng-model="post.title" id="title" required="required">
</div>
<input type="submit" value="Submit">
</form>
I looked this error up and everything I am seeing has nothing to do with what my set up is like.
Please help me out on this. I don't know where to go from here.
Thanks
Try this...
you have initialized $scope.post = ''; as a string. But that should be $scope.post = {}; an object.
var mainApp = angular.module('app', []);
mainApp.controller('newPostController', ['$scope', '$http', function($scope, $http) {
$scope.post = {};
$scope.postCreated = false;
$scope.makeNewPost = function() {
console.log($scope.post.title);
$http.post('/api/post', {
title: $scope.post.title,
})
.then(function(res) {
$scope.postCreated = true;
//extra code not related to the form itself...
});
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app='app' ng-controller='newPostController'>
<form ng-submit="makeNewPost()">
<div class="form-group">
<label for="title" class="control-label">Title</label>
<input type="text" autocomplete="off" class="form-control" ng-model="post.title" id="title" required="required">
</div>
<input type="submit" value="Submit">
</form>
</div>

$auth.login is not a function

I'm using AngularJS 1.4.6 and Satellizer for oauth.
I'm doing everything as written but always get same error:
angular.js:12450 TypeError: $auth.login is not a function
login.html:
<div class="form-group">
<input type="email" class="form-control underline-input" placeholder="Email" ng-model="user.email" required>
</div>
<div class="form-group">
<input type="password" placeholder="Password" class="form-control underline-input" ng-model="user.password" required>
</div>
<div class="form-group text-left mt-20">
<button type="submit" class="btn btn-greensea b-0 br-2 mr-5" ng-click="login()" ng-disabled='form.$invalid'>Login</button>
<label class="checkbox checkbox-custom checkbox-custom-sm inline-block">
<input type="checkbox"><i></i> Remember me
</label>
<a ui-sref="core.forgotpass" class="pull-right mt-10">Forgot Password?</a>
</div>
</form>
Login controller:
.controller('LoginCtrl', function ($scope, $auth) {
$scope.user = {};
$scope.user.email = 'test#gmail.com';
$scope.user.password = 'test';
$scope.login = function () {
$auth.login($scope.user).then (
function (response) {
console.log(response);
},
function (error) {
console.log(error);
}
)
}
app.js:
.config(['$stateProvider', '$urlRouterProvider', '$authProvider', function($stateProvider, $urlRouterProvider, $authProvider ) {
$authProvider.loginUrl = '/auth/login';
...
I tried different settlements, researched github issues but not found a solution.
Whats my fault? How can I fix it?
I add to controller array option
.controller('LoginCtrl', ['$scope','$auth', function ($scope, $auth) {
$scope.user = {};
$scope.user.email = 'test#gmail.com';
$scope.user.password = 'test';
$scope.login = function () {
$auth.login($scope.user).then (
function (response) {
console.log(response);
},
function (error) {
console.log(error);
}
)
}]

Cannot get the variable in ng-model in directive template

I have a directive for comment input as follows, I want to reset the form after the user posted the comment. However, I can not get the newComment value of ng-model in link function. How to solve such problem.
commenting.html
<div class="directive__commenting">
<div class="col-content">
<h4>{{title}}({{count}})</h4>
<form class="form" name="commentForm" ng-submit="createComment(commentForm, newComment)" ng-if="isLoggedIn()">
<div class="form-group">
<textarea class="form-control" name="newComment" rows="3" placeholder="你怎么看?" ng-model="newComment" required></textarea>
</div>
<div class="right">
<span id="count-words" ng-class="{'red': isWordsExceeded(newComment)}">{{140 - newComment.length}}</span>
<button class="send-button btn btn-default" type="submit" ng-disabled="isWordsExceeded()">{{btnActionTitle}}</button>
</div>
</form>
</div>
</div> <!-- #create-comment -->
commenting.directive.js
'use strict';
angular.module('myapp')
.directive('commenting', function (Auth) {
return {
templateUrl: 'components/directive/commenting/commenting.html',
restrict: 'EA',
scope: {
title: '=',
count: '=',
btnActionTitle: '=',
action: '='
},
link: function (scope) { //, element, attrs
scope.isLoggedIn = Auth.isLoggedIn;
scope.isWordsExceeded = function (newComment) {
return newComment && newComment.length > 140;
}; //- isWordsExceeded
scope.createComment = function (form, newComment) {
scope.action(form, newComment)
.then(function () { //success
// clear the form, however here scope.newComment is undefined
})
.catch(function () { //fail
});
};
}
};
});
The directive is added in a html file as follows.
<div class="row" id="create-comment">
<commenting title="'Comments'" count="model.comments.length" btn-action-title="'Submit comment'" action="createComment"></commenting>
</div> <!-- #create-comment -->
Try to access through scope like
scope.newComment

Controller and input form html use var Javascript

I use the angularjs framework, I created an form.html and a controller.js with a variable that retrieves the SSID of a box.
How to automatically assign the value of the variable in the form.
This is an input field.
When launching the application, the form should display the SSID automatically without the user needing to do so.
Thank you kindly help me.
'use strict';
angular.module('djoro.controllers')
.controller('WifiSmartConfigCtrl', function ($scope, $window, $ionicPlatform) {
$scope.getSSID = function () {
var onSuccess = function (SSID) {
document.write(SSID);
};
var onFail = function () {
};
$ionicPlatform.ready(function () {
$window.cordova.plugins.Smartconfig.getSSID(onSuccess, onFail);
});
};
});
<ion-pane>
<ion-content ng-controller="WifiSmartConfigCtrl">
<form novalidate class="simple-form">
<fieldset>
<legend>WI-FI</legend>
<div class="list input-fields">
<label class="item item-input">
<span class="input-label">SSID :</span>
<input type="text" name="test" value="getSSID()" required show-hide-input>
</label>
<label class="item item-input" show-hide-container>
<span class="input-label">Password :</span>
<input type="text" name="password" required show-hide-input>
</label>
</div>
</fieldset>
</form>
</ion-content>
</ion-pane>
use the ng-model directive, it's exactly it's purpose :
'use strict';
angular.module('djoro.controllers')
.controller('WifiSmartConfigCtrl', function($scope, $window, $ionicPlatform) {
$scope.SSID = {};
$scope.getSSID = function() {
var onSuccess = function(SSID) {
$scope.SSID = SSID;
};
var onFail = function() {};
$ionicPlatform.ready(function() {
$window.cordova.plugins.Smartconfig.getSSID(onSuccess, onFail);
});
};
});
and in your view :
<input type="text" name="test" ng-model="SSID" required show-hide-input>
You need to add an ng-model to the input field like so:
<label class="item item-input">
<span class="input-label">SSID :</span>
<input type="text" name="test" ng-model="SSID" required show-hide-input>
</label>
then in your controller assign the value of SSID on the $scope:
$scope.SSID = [some_value]
see this plnkr
As you can see I have assigned the value of SSID manually, you can add it dynamically by assigning it in the callback of your function like so:
$scope.SSID = {}
var onSuccess = function (SSID) {
document.write(SSID);
$scope.SSID = SSID
};

Categories