i'm a newbie in angular JS. and i was trying the input type="text", i'm retrieving my name from my controller and i was using $dirty and $invalid to validate my data but it isn't showing when i make the input field empty.
JS Fiddle : https://jsfiddle.net/U3pVM/24718/
var FormValidations = angular.module('FormValidations',[]);
FormValidations.controller('FormsValidations', function( $scope ){
$scope.formsToBeValidated = {
firstName : 'Daniel'
};
});
Unless you add name attribute to form level field, that will not get included in form object when you specified in the name attribute on form, currentlyh it is name="studentForm". Do add name="firstName" to your input field
<input type="text" class="form-control"
name="firstName" ng-model="formsToBeValidated.firstName" required/>
Forked Fiddle
For more information you could refer this answer, which has more detailed
More convenient way to solve this issue would be using ng-messages instead of using ng-show/ng-hide, for that you have to include ng-messages module with its ng-messages dependency.
you should try this:
<input name="firstName" type="text" class="form-control"
ng-model="formsToBeValidated.firstName" required>
fiddle
as other says , add "name" attribute to your input.
I made a custom directive to display error on input using ng-message ( so you have to include it )
directives.directive('inputerrormsg', function () {
return {
replace: true,
restrict: 'E',
plain: true,
scope: {
inputdata: "=",
dpattern: '#'
},
template: '<div class="help-block has-error text-center" ng-messages="inputdata[\'$error\']" >' +
'<p ng-message="required">{{\'The field is required\'| translate }}</p>' +
'<p ng-message="minlength">{{\'Input too short\'| translate }}</p>' +
'<p ng-message="maxlength">{{\'Input too long\'| translate }}</p>' +
'<p ng-message="email">{{\'Email invalid\'| translate }}</p>' +
'<p ng-message="date">{{\'Date invalid\'| translate }}</p>' +
'<p ng-message="number">{{\'Write number only\'| translate }}</p>' +
'<p ng-message="pattern">' +
'<span ng-switch="dpattern">' +
'<span ng-switch-when="date">{{\'Date incorrecte: YYYY, YYYY/MM, YYYY/MM/DD\' |translate}}</span>' +
'<span ng-switch-default>{{\'Saisir uniquement des lettres\'| translate }}</span>' +
'</span>' +
'</p>' +
'</div>'
}
});
USAGE :
required field
<div style="padding-left: 0px;" ng-class="{ 'has-error' : !formDeter.scientificname.$valid">
<div class="input-group no-padding">
<input type="text"
class="form-control input-md" name="scientificname"
required />
<span class="input-group-addon">
<span class="glyphicon glyphicon-question-sign"></span>
</span>
</div>
<dir.inputerrormsg inputdata="formDeter.scientificname" ></dir.inputerrormsg>
EMail :
<div class="form-group row" ng-class="{ 'has-error' : !formData.email.$valid }">
<label class="col-xs-4 control-label">{{"Email" | translate }}</label>
<div class="col-xs-8 input-group">
<input type="email" class="form-control input-md" ng-model="email" name="email" id="email" required
placeholder="{{'Email' | translate }}"/>
</div>
<dir.inputerrormsg inputdata="formData.email" dpattern="email" ></dir.inputerrormsg>
</div>
Number only :
<div class="form-group row" ng-class="{ 'has-error' : !formLocalisation.decimallongitude.$valid }">
<label class="col-xs-4 control-label">{{"Longitude" | translate }}</label>
<div class="col-xs-8 input-group">
<input type="number" popover-trigger="focus" placeholder="{{'Longitude' | translate }}"
class="form-control input-md"
ng-model="specimen.decimallongitude" name="decimallongitude"
/>
<span class="input-group-addon" >
<span class="glyphicon glyphicon-question-sign"></span>
</span>
</div>
<dir.inputerrormsg inputdata="formLocalisation.decimallongitude" ></dir.inputerrormsg>
</div>
...
You didn't specified name to your input. Try this:
<form name="studentForm" novalidate>
<input type="text" class="form-control" name ="input" ng-model="formsToBeValidated.firstName" required>
<span studentForm.input.$error.required && studentForm.input.$dirty>First Name is Required</span>
</form>
Related
I am newbie in angularjs. I have create directive called newActivity and bind object, variables and function with this directive. Here i want that when i clicked on submit/cancel button then it should clear all ng-model bind variables from both newActivity directive and from controller.
Example
Directive:-
angular
.module('app')
.directive('newActivity', newActivity);
function newActivity() {
var directive = {
restrict: 'E',
scope: {
newActivity: '=',
underUsers: '=',
actTypes: '=',
callTypes: '=',
forAct: '#',
action: '&',
cancel: '&'
},
template: '<div class="box-header"> <h2>{{forAct}} {{newActivity.type | uppercase}} Activity</h2> </div> <div class="box-divider m-a-0">' +
'</div> <div class="box-body"> <form ng-submit="action()" name="newActForm" role="form">' +
'<div class="form-group row"><div class="col-sm-10"><select class="form-control" ng-model="newActivity.type" ng-options="actType.type as actType.title for actType in actTypes"></select></div></div> ' +
'<div ng-if="newActivity.type==\'notes\'" class="form-group row"><div class="col-sm-10"><textarea required ng-model="newActivity.description" class="form-control" rows="2"></textarea></div></div> ' +
'<div ng-if="newActivity.type==\'meeting\' || newActivity.type==\'email\' || newActivity.type==\'task\'" class="form-group row"><div class="col-sm-10">' +
'<div class="form-group row"><div class="col-sm-10"><input required placeholder="Select Date" type="text" class="form-control w-auto inline" ng-model="newActivity.date" data-date-format="dd-MM-yyyy" data-autoclose="true" data-date-type="number" data-icon-left="fa fa-chevron-left" data-icon-right="fa fa-chevron-right" placeholder="From" bs-datepicker></div></div>' +
'<div class="form-group row"><div class="col-sm-10"><input required placeholder="Select Time" type="text" class="form-control" ng-model="newActivity.time" data-time-format="HH:mm" data-time-type="number" name="time2" data-icon-up="fa fa-chevron-up" data-icon-down="fa fa-chevron-down" bs-timepicker></div></div>' +
'<div class="form-group row"> <label class="col-sm-4 form-control-label">Reminder</label> <div class="col-sm-8"> <div class="checkbox"> <label class="ui-switch m-t-xs m-r"> <input type="checkbox" ng-model="newActivity.isReminder" value=""> <i></i> </label> </div> </div> </div>' +
'<div ng-if="newActivity.isReminder" col-sm-8>' +
'<div class="form-group row"><div class="col-sm-10"><input required placeholder="Reminder Date" type="text" class="form-control w-auto inline" ng-model="newActivity.reminder.date" data-icon-left="fa fa-chevron-left" data-date-format="dd-MM-yyyy" data-autoclose="true" data-date-type="number" data-icon-right="fa fa-chevron-right" placeholder="From" bs-datepicker></div></div> ' +
'<div class="form-group row"><div class="col-sm-10"><input required placeholder="Reminder Time" type="text" class="form-control" ng-model="newActivity.reminder.time" data-time-format="HH:mm" data-time-type="number" name="time1" data-icon-up="fa fa-chevron-up" data-icon-down="fa fa-chevron-down" bs-timepicker></div></div> ' +
'</div>' +
'<div class="form-group row"> <label class="col-sm-4 form-control-label">Assign To Other</label> <div class="col-sm-8"> <div class="checkbox"> <label class="ui-switch m-t-xs m-r"> <input type="checkbox" ng-model="newActivity.isAssignOther" value=""> <i></i> </label> </div> </div> </div>' +
'<div ng-if="newActivity.isAssignOther" col-sm-8>' +
'<div class="form-group row"><div class="col-sm-10"><select class="form-control" ng-model="newActivity.assignTo" ng-options="user._id as user.name for user in underUsers"></select></div></div> ' +
'</div>' +
'<div class="form-group row"><div class="col-sm-10"><textarea required placeholder="Remarks" class="form-control" ng-model="newActivity.description" rows="2"></textarea></div></div>' +
'</div></div> ' +
'<div ng-if="newActivity.type==\'call\'" class="form-group row"><div class="col-sm-10">' +
'<div class="form-group row"><div class="col-sm-10"><select class="form-control" ng-init="newActivity.callType = \'out\'" ng-model="newActivity.callType" ng-options="callType.type as callType.title for callType in callTypes"></select></div></div>' +
'<div class="form-group row"><div class="col-sm-10"><input required placeholder="Select Date" type="text" class="form-control w-auto inline" ng-model="newActivity.date" data-date-format="dd-MM-yyyy" data-autoclose="true" data-date-type="number" data-icon-left="fa fa-chevron-left" data-icon-right="fa fa-chevron-right" placeholder="From" bs-datepicker></div></div>' +
'<div class="form-group row"><div class="col-sm-10"><input required placeholder="Select Time" type="text" class="form-control" ng-model="newActivity.time" data-time-format="HH:mm" data-time-type="number" name="time2" data-icon-up="fa fa-chevron-up" data-icon-down="fa fa-chevron-down" bs-timepicker></div></div>' +
'<div class="form-group row"> <label class="col-sm-4 form-control-label">Reminder</label> <div class="col-sm-8"> <div class="checkbox"> <label class="ui-switch m-t-xs m-r"> <input type="checkbox" ng-model="newActivity.isReminder" value=""> <i></i> </label> </div> </div> </div>' +
'<div ng-if="newActivity.isReminder" col-sm-8>' +
'<div class="form-group row"><div class="col-sm-10"><input required placeholder="Reminder Date" type="text" class="form-control w-auto inline" ng-model="newActivity.reminder.date" data-icon-left="fa fa-chevron-left" data-date-format="dd-MM-yyyy" data-autoclose="true" data-date-type="number" data-icon-right="fa fa-chevron-right" placeholder="From" bs-datepicker></div></div> ' +
'<div class="form-group row"><div class="col-sm-10"><input required placeholder="Reminder Time" type="text" class="form-control" ng-model="newActivity.reminder.time" data-time-format="HH:mm" data-time-type="number" name="time1" data-icon-up="fa fa-chevron-up" data-icon-down="fa fa-chevron-down" bs-timepicker></div></div> ' +
'</div>' +
'<div class="form-group row"> <label class="col-sm-4 form-control-label">Assign To Other</label> <div class="col-sm-8"> <div class="checkbox"> <label class="ui-switch m-t-xs m-r"> <input type="checkbox" ng-model="newActivity.isAssignOther" value=""> <i></i> </label> </div> </div> </div>' +
'<div ng-if="newActivity.isAssignOther" col-sm-8>' +
'<div class="form-group row"><div class="col-sm-10"><select class="form-control" ng-model="newActivity.assignTo" ng-options="user._id as user.name for user in underUsers"></select></div></div> ' +
'</div>' +
'<div class="form-group row"><div class="col-sm-10"><textarea required placeholder="Remarks" class="form-control" ng-model="newActivity.description" rows="2"></textarea></div></div>' +
'</div></div> ' +
'<div class="form-group row m-t-md"> <div class="col-sm-offset-2 col-sm-10">' +
'<input type="submit" class="btn success" value="Save">' +
'<button type="button" style="margin-left:5px" ng-click="cancel()" class="btn danger">Cancel</button>' +
'</div></form> </div>',
link: function(scope, element, attrs) {},
controller: function($scope) {}
};
return directive;
}
Controller:-
function addNewActivity() {
vm.loading = true;
vm.newActivity = {}; //Here vm.newActivity is not clear fields from "newActivity" directive
}
HTML:-
<new-activity for-act='Add' action='addNewActivity()' cancel='closeAddNewActivity()' new-activity='newActivity' under-users='underUsers' act-types='actTypes' call-types='callTypes'></new-activity>
You are using the controllerAs synthax, you should prefix your calls to functions and use of variables with the name you specify (here vm).
For example if your code:
<new-activity for-act='Add'
action='addNewActivity()'
cancel='closeAddNewActivity()'
new-activity='newActivity'
under-users='underUsers'
act-types='actTypes'
call-types='callTypes'>
</new-activity>
Shoud be:
<new-activity for-act='Add'
action='vm.addNewActivity()'
cancel='vm.closeAddNewActivity()'
new-activity='vm.newActivity'
under-users='vm.underUsers'
act-types='vm.actTypes'
call-types='vm.callTypes'>
</new-activity>
Use new-activity='vm.newActivity' instead of new-activity='newActivity
And also use vm.addNewActivity() and vm.closeAddNewActivity()
So that every bindings have the correct source from your controller
<new-activity for-act='Add' action='vm.addNewActivity()' cancel='vm.closeAddNewActivity()' new-activity='vm.newActivity' under-users='vm.underUsers' act-types='vm.actTypes' call-types='vm.callTypes'></new-activity>
I am trying to show error message after validation. Backend is php and it is returning the data i can see that in network tab.
Here are the codes.
function formRegister($scope, $http) {
// create a blank object to hold our form information
// $scope will allow this to pass between controller and view
$scope.formData = {};
$scope.registerForm = function() {
$http({
method : 'POST',
url : 'registerexec.php',
data : $.param($scope.formData), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
console.log(data);
if (!data.success) {
// if not successful, bind errors to error variables
//{{$scope.errorFname}}
$scope.erroracType = data.errors.actype;
$scope.errorFname = data.errors.Fname;
$scope.errorLname = data.errors.Lname;
$scope.errorEmail1 = data.errors.email1;
$scope.errorPassword1 = data.errors.password1;
$scope.errormobile = data.errors.mobile;
$scope.message1 = data.message1;
}
});
};
}
Here is the form.
<div class="feature-box wow animated flipInX animated">
<div id="validation-errorss" ng-show="message1" ><div class="alert alert-danger"><strong >{{ message1 }}</strong><div></div></div>
</div>
<div class="panel-body" id="success"></div>
<font size="4" color="#fff">Register</font>
<form name="register" method="post" id="register" role="form" ng-submit="registerForm()">
<div class="form-group" ng-class="{ 'has-error' : erroractype }">
<select id="actype" name="actype" class=" selector form-control" ng-model="formData.actype" required="required">
<option value="" selected="selected" >I am</option>
<option value="1">a user</option>
<option value="2">an admin</option>
</select>
<span class="help-block" ng-show="errorName">{{ erroractype }}</span>
</div>
<div class="form-group" ng-class="{ 'has-error' : errorFname }">
<input type="text" id="fname" name="fname" placeholder="First Name" title="Please Enter Your First Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Fname">
<span class="help-block" ng-show="errorFName">{{ errorFname }}</span>
</div>
<div class="form-group" ng-class="{ 'has-error' : errorLname }">
<input type="text" id="lname" name="lname" placeholder="Last Name" title="Please Enter Your Last Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Lname">
<span class="help-block" ng-show="errorLName">{{ errorLname }}</span>
</div>
<div class="form-group" ng-class="{ 'has-error' : errorEmail1 }">
<input type="email" id="email1" name="email1" placeholder="Email" class="form-control input-sm textbox1" title="Please Enter Your Valid Email" required="required" ng-model="formData.Email1">
<span class="help-block" ng-show="errorEmail1">{{ errorEmail1 }}</span>
</div>
<div class="form-group" ng-class="{ 'has-error' : errorPassword1 }">
<input type="password" name="password1" id="password1" placeholder="Password" title="Please enter AlphaNumeric value" class="form-control input-sm textbox1" required="required" ng-model="formData.Password1">
<span class="help-block" ng-show="errorPassword1">{{ errorPassword1 }}</span>
</div>
<div class="form-group" ng-class="{ 'has-error' : errormobile }">
<input type="text" id="mobile" name="mobile" placeholder="Mobile Number (Without +91)" title="Please Enter Your Contact Number without Coutry Code." class="form-control input-sm textbox1" required="required" ng-model="formData.mobile">
<span class="help-block" ng-show="errormobile">{{ errormobile }}</span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-home" name="btn-register" id="btn-register" required="required">Register</button>
</div>
</form>
Problem is when form get validated in backend. The array messages are not showing in .
Here are the validation errors which found in firebug.
errors:Object Fname:"Your First name must be between 3 to 30
characters!" Lname:"Your Last name must be between 3 to 30
characters!" Password1:"Your password must be between 6 to 30
characters!" success:false
Add novalidate attribute to form tag
<form novalidate>
You might use this if you plan to do your own client-side validation, if you want to create your own validation bubbles, or if you plan to go all server-side validation (which you need to do anyway).
My error description:
step 1: I am appending template using this directive.
step 2: Now I remove this appended template using this scope function "removeMilestoneDiv".
step 3: After submit my form. But, I can't submitted.
I think I have add template then bind this scope variable. But, i have remove this template then scope variable is can't unbind.
Create directive for add milestone:
app.directive('addMilestone', ['$compile', function ($compile) { // inject $compile service as dependency
return {
restrict: 'A',
link: function (scope, element, attrs) {
// click on the button to add new input field
element.find('a').bind('click', function () {
// I'm using Angular syntax. Using jQuery will have the same effect
// Create input element
// var input = angular.element('<div id="scope.mileStoneId_'+ scope.mileStoneCounter +'" class="form">Milestone - '+scope.mileStoneCounter+'</div>');
var input = angular.element(''+
'<div class="card bg-white" id="mileStoneDiv_'+ scope.mileStoneCounter +'">'+
'<div class="card-header" ng-bind="\'project.ADD_MILESTONE\' | translate"></div>'+
''+
'<div class="card-block m-b-0">'+
'<div compile-template class="form-group">'+
'<label class="col-sm-2 control-label"><span ng-bind="\'project.COMPANY_MILESTONE_ID\' | translate"></span></label>'+
'<div class="col-sm-5">'+
'<input type="text" class="form-control" ng-model="company_milestone_id['+ scope.mileStoneCounter +']" ng-maxlength="100" name="company_milestone_id_'+ scope.mileStoneCounter +'" required>'+
'<div ng-messages="frmProjectAdd[\'company_milestone_id_'+scope.mileStoneCounter+'\'].$error" role="alert" class="help-block has-error">'+
'<span ng-message="required" class="help-block has-error">Company Milestone Id is required.</span>'+
'<span class="help-block has-error" ng-message="maxlength">Maximum 100 characters allowed!</span>'+
'</div>'+
'</div>'+
'</div>'+
'<div compile-template class="form-group">'+
'<label class="col-sm-2 control-label" ng-bind="\'project.MILESTONE_NAME\' | translate"></label>'+
'<div class="col-sm-5">'+
'<input type="text" ng-maxlength="100" class="form-control" ng-model="milestone_name['+ scope.mileStoneCounter +']" name="milestone_name_'+ scope.mileStoneCounter +'" required>'+
'<div ng-messages="frmProjectAdd[\'milestone_name_'+scope.mileStoneCounter+'\'].$error" class="has-error login-error">'+
'<span ng-message="required" class="help-block has-error">Milestone Name is required.</span>'+
'</div>'+
'</div>'+
'</div>'+
'<div compile-special-template class="form-group">'+
'<label class="col-sm-2 control-label" ng-bind="\'project.SELECT_EMPLOYEE\' | translate"></label>'+
'<div class="col-sm-10">'+
'<select style="min-width:250px;" ui-select2 name="select_new_employee_'+scope.mileStoneCounter+'" ng-model="selectEmployee['+ scope.mileStoneCounter +']" data-placeholder="Select Employee" ng-required="true" multiple>'+
'<option ng-repeat="manager in managerList" value="{{manager.id}}">{{manager.username}}</option>'+
'</select>'+
'</div>'+
'<div ng-messages="frmProjectAdd[\'select_new_employee_'+scope.mileStoneCounter+'\'].$error" class="has-error login-error">'+
'<span ng-message="required" class="help-block has-error">Employee is required.</span>'+
'</div>'+
'</div>'+
'</div>');
// Compile the HTML and assign to scope
var compile = $compile(input)(scope);
// Append input to div
$('#milestoneHtml').append(input);
// Increment the counter for the next input to be added
scope.mileStoneCounter++;
});
}
}
}]);
Remove milestone using this function:
$scope.removeMilestoneDiv = function(key, id, flag) {
var confirmVal = confirm("Are you sure you want to delete this Milestone?");
if(confirmVal) {
$('#mileStoneDiv_'+key).remove();
if(flag == 1){
if(id != 0) {
$scope.deletedMilestoneIds.push(id);
}
}
}
},
Create One Array:
$scope.mileStoneCounterNew = [{
'countId':1,
'company_milestone_id':'',
'milestone_name':'',
'milestone_start_date':'',
'milestone_end_date':'',
'milestone_completion_date':'',
'selectEmployee':'',
}];
Create one scope function
$scope.milestoneHtmlAdd = function() {
$scope.mileStoneCounter++;
var counterObj = {countId: $scope.mileStoneCounter };
$scope.mileStoneCounterNew.push(counterObj);
};
My Dynamic HTML
<!-- Add Milestone - Start -->
<div class="row" ng-repeat="(counterKey, counterValue) in mileStoneCounterNew" id="milestone_display_id_{{counterValue.countId}}">
<div class="card bg-white mt50">
<div class="card-header"><span ng-bind="'project.ADD_MILESTONE' | translate"></span></div>
<a ng-if="counterKey > 0" href="javascript:void(0)" class="removebtn glyphicon glyphicon-remove form-control-feedback" ng-click="milestoneDivRemove(counterKey,0,0)"></a>
<div class="card-block m-b">
<!--Milestone sub section-->
<!-- Company Milestone Id -->
<div class="form-group">
<label class="col-sm-2 control-label"><span ng-bind="'project.COMPANY_MILESTONE_ID' | translate"></span></label>
<div class="col-sm-5">
<input type="text" class="form-control" ng-model="counterValue.company_milestone_id" ng-maxlength="100" name="company_milestone_id_{{counterValue.countId}}" required>
<div ng-if="frmProjectAdd.$submitted || frmProjectAdd['company_milestone_id_'+counterValue.countId].$touched" ng-messages="frmProjectAdd['company_milestone_id_'+counterValue.countId].$error" role="alert" class="help-block has-error">
<span ng-message="required" class="help-block has-error">Company Milestone Id is required.</span>
<span class="help-block has-error" ng-message="maxlength">Maximum 100 characters allowed!</span>
</div>
</div>
</div>
<!-- Milestone name -->
<div class="form-group">
<label class="col-sm-2 control-label"><span ng-bind="'project.MILESTONE_NAME' | translate"></span></label>
<div class="col-sm-5">
<input type="text" class="form-control" ng-model="counterValue.milestone_name" ng-maxlength="100" name="milestone_name_{{counterValue.countId}}" required>
<div ng-if="frmProjectAdd.$submitted || frmProjectAdd['milestone_name_'+counterValue.countId].$touched" ng-messages="frmProjectAdd['milestone_name_'+counterValue.countId].$error" role="alert" class="help-block has-error">
<span ng-message="required" class="help-block has-error">Milestone Name is required.</span>
<span class="help-block has-error" ng-message="maxlength">Maximum 100 characters allowed!</span>
</div>
</div>
</div>
<!-- Milestone Start Date -->
<div class="form-group">
<label class="col-sm-2 control-label"><span ng-bind="'project.MILESTONE_START_DATE' | translate"></span></label>
<div class="col-sm-3">
<div class="input-group">
<input name="milestone_start_date_{{counterValue.countId}}" type="text" uib-datepicker-popup="MM/dd/yyyy" ng-model="counterValue.milestone_start_date" is-open="dpOpened['milestone_start_date_'+counterValue.countId]" ng-click="milestone_start_date[counterValue.countId].open = true" max-date="maxDate" datepicker-options="dateOptions" close-text="Close" ng-required="true" class="form-control"
min-date="minDate" ng-change="set_min_milestone_end_Date(milestone_start_date[counterValue.countId])"
disabled>
<span class="input-group-addon" ng-click="open($event,'milestone_start_date_{{counterValue.countId}}')"><i class="fa fa-calendar"></i></span>
</div>
<div ng-if="frmProjectAdd.$submitted || frmProjectAdd['milestone_start_date_'+counterValue.countId].$touched" ng-messages="frmProjectAdd['milestone_start_date_'+counterValue.countId].$error" role="alert" class="help-block has-error">
<span ng-message="required" class="help-block has-error">Milestone Start Date is required.</span>
</div>
</div>
</div>
<!-- Milestone End Date -->
<div class="form-group">
<label class="col-sm-2 control-label"><span ng-bind="'project.MILESTONE_END_DATE' | translate"></span></label>
<div class="col-sm-3">
<div class="input-group">
<input name="milestone_end_date_{{counterValue.countId}}" type="text" uib-datepicker-popup="MM/dd/yyyy" ng-model="counterValue.milestone_end_date" is-open="dpOpened['milestone_end_date_'+counterValue.countId]" ng-click="milestone_end_date[counterValue.countId].open = true" max-date="maxDate" datepicker-options="dateOptions" close-text="Close" ng-required="true" class="form-control"
min-date="milestone_end_minDate" ng-change="set_min_milestone_completed_Date(milestone_end_date[counterValue.countId])"
disabled>
<span class="input-group-addon" ng-click="open($event,'milestone_end_date_{{counterValue.countId}}')"><i class="fa fa-calendar"></i></span>
<div ng-if="frmProjectAdd.$submitted || frmProjectAdd['milestone_end_date_'+counterValue.countId].$touched" ng-messages="frmProjectAdd['milestone_end_date_'+counterValue.countId].$error" role="alert" class="help-block has-error">
<span ng-message="required" class="help-block has-error">Milestone End Date is required.</span>
</div>
</div>
</div>
</div>
<!-- Milestone Completion Date -->
<div class="form-group">
<label class="col-sm-2 control-label"><span ng-bind="'project.MILESTONE_COMPLETION_DATE' | translate"></span></label>
<div class="col-sm-3">
<div class="input-group">
<input type="text" uib-datepicker-popup="MM/dd/yyyy" ng-model="counterValue.milestone_completion_date" is-open="dpOpened['milestone_completion_date_'+counterValue.countId]" ng-click="milestone_completion_date[counterValue.countId].open = true" max-date="maxDate" datepicker-options="dateOptions" close-text="Close" class="form-control"
min-date="milestone_completed_minDate" disabled>
<span class="input-group-addon" ng-click="open($event,'milestone_completion_date_{{counterValue.countId}}')"><i class="fa fa-calendar"></i></span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"><span ng-bind="'project.SELECT_EMPLOYEE' | translate"></span></label>
<div class="col-sm-10">
<select name="select_employee_{{counterValue.countId}}" ui-select2 ng-model="counterValue.selectEmployee" data-placeholder="Select Employee" ng-required="true" multiple>
<option ng-repeat="manager in managerList" value="{{manager.id}}">{{manager.username}}</option>
</select>
<div ng-if="frmProjectAdd.$submitted || frmProjectAdd['select_employee_'+counterValue.countId].$touched" ng-messages="frmProjectAdd['select_employee_'+counterValue.countId].$error" role="alert" class="help-block has-error">
<span ng-message="required" class="help-block has-error">Employee is required.</span>
</div>
</div>
</div>
<!-- Milestone sub section -->
</div>
</div>
</div>
<!-- Add Milestone End -->
I am trying to reset the form after the submit button is clicked. I understand that setting the form to pristine alone should not clear the input fields. I tried implementing the various suggestions to clear form by setting the form to pristine and then assigning null to all input fields. Is there a more neat way to implement it ?
Template:
<p>{{contactForm.$pristine}}</p>
<div class="inBox">
<form name="contactForm" novalidate>
<div class="form-group" ng-class="{ 'has-error' : contactForm.name.$invalid && !contactForm.name.$pristine }">
<label>Name</label>
<input type="text" ng-model="tabVm.name" class="form-control" name="name" required>
<p ng-show="contactForm.name.$invalid && !contactForm.name.$pristine" class="help-block">You name is required.</p>
</div>
<div class="form-group" ng-class="{ 'has-error' : contactForm.email.$invalid && !contactForm.email.$pristine }">
<label>Email</label>
<input type="email" ng-model="tabVm.email" name="email" class="form-control" required>
<p ng-show="contactForm.email.$invalid && !contactForm.email.$pristine" class="help-block">Enter a valid email.</p>
</div>
<div class="form-group">
<label>Contact Number</label>
<input type="tel" ng-model="tabVm.number" class="form-control">
</div>
<div class="form-group" ng-class="{ 'has-error' : contactForm.message.$invalid && !contactForm.message.$pristine }">
<label>Message</label>
<textarea type="text" rows="5" ng-model="tabVm.message" name="message" class="form-control textBox" required></textarea>
<p ng-show="contactForm.message.$invalid && !contactForm.message.$pristine" class="help-block">Brief message is required.</p>
</div>
</form>
<button type="submit" ng-click="sendMsg()" class="btn large-btn"
ng-disabled="contactForm.message.$invalid || contactForm.name.$invalid||contactForm.email.$invalid " >Send</button>
</div>
app.js
$scope.contactForm.$setPristine();
and I also tried
$scope.contactForm.$pristine=true;
Neither of them seem to work. I use angular 1.4.8.
Thank you.
You should use $setPristine() and then reset the ng-model object. Also pay attention you have the submit button outside the <form>.
This is a working JSFiddle (I used only one input for example)
$scope.sendMsg = function() {
$scope.contactForm.$setPristine();
$scope.tabVm = {};
}
You referenced controlForm, but the html you posted have contactForm
I finally got it working by making the following changes :
<div class="container box col-lg-6" >
<p>{{contactForm.$pristine}}</p>
<p>name state: {{contactForm.name.$pristine}}</p>
<div class="inBox">
<form name="contactForm" ng-submit="sendMsg(contactForm)" novalidate>
<div class="form-group" ng-class="{ 'has-error' : contactForm.name.$invalid && !contactForm.name.$pristine }">
<label>Name</label>
<input type="text" ng-model="tabVm.name" class="form-control" name="name" required>
<p ng-show="contactForm.name.$invalid && !contactForm.name.$pristine" class="help-block">You name is required.</p>
</div>
<input type="submit" class="btn large-btn"
ng-disabled="contactForm.message.$invalid || contactForm.name.$invalid||contactForm.email.$invalid " >
</form>
</div>
</div>
and app.js :
$scope.sendMsg=function(form){
if(form.$valid){
console.log("Form is valid"); //this was a check I used to confirm that the controller recognized the form.
}
form.$setPristine();
tabVm.name="";
}
}
I do not clearly understand why this works or what was I doing wrong earlier. I would appreciate if anyone could explain. Thank you.
Do as follows
$scope.sendMsg = function(){
//your function code
$scope.tabVm={};
$scope.tabVm.name='';
$scope.tabVm.email='';
$scope.tabVm.number='';
$scope.tabVm.message='';
}
I'm trying to POST from an AngularJS Form to a PHP emailing file.
I've been struggling with this problem and I have tried almost everything related to $scope and controllers but with nothing useful at all, but what I ended up with after troubleshooting is that the second I remove the <form> html tag within my partial view, the error disappears, but also the ng-submit would not work since it is within the <form> tag.
I have 2 controllers for the same view, and tried to use only 1 controller but had the same error appear again and again with everything I tried, within the view, and within the controller, except for the <form> tag as I just said.
This is my controller code:
<script>
myApp.controller('FormController',
function($scope, $http, $window) {
$scope.CompanyEmail = $window.email;
$scope.formData = {};
$scope.processForm = function(formData) {
//console.log(formData);
$http({
method : 'POST',
url : { 'templateUrl' : 'angularjs-app/views/contact_us.php' },
data : $.param($scope.formData),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data) {
//console.log(data);
if(!data.success) {
$scope.errorFirstName = data.errors.firstname;
$scope.errorLastName = data.errors.lastname;
$scope.errorPhone = data.errors.phone;
$scope.errorEmail = data.errors.c_email;
$scope.errorCompany = data.errors.company;
$scope.errorComment = data.errors.comment;
} else {
$scope.message = data.message;
}
});
}
}
);
</script>
<div ng-controller="contact_us">
<h2 style="margin: 20px;">
{{subject}}
</h2>
<p style="font-size: 15px; margin: 20px;" >
{{body}}
</p>
<div id="contact" style="float: right; " ng-controller="FormController">
<h2 style="margin-right: 30px"> TITLE </h2>
<p id="article"> PARAGRAPH </p>
<!-- SHOW ERROR/SUCCESS MESSAGES -->
<div id="messages" ng-show="message">{{ message }}</div>
<form enctype="multipart/form-data" id="form" name="form" accept-charset="UTF-8" ng-submit="processForm()" >
<input type="hidden" name="CompanyEmail" ng-value="CompanyEmail" />
<div id="first-name-group" class="form-group" ng-class="{ 'has-error' : errorFirstName }">
<label> Name *<br> </label>
<input type="text" name="firstname" id="firstname" placeholder=" " required class="form-control" ng-model="formData.firstname">
<span class="help-block" ng-show="errorFirstName">{{ errorFirstName }}</span>
</div>
<div id="last-name-group" class="form-group" ng-class="{ 'has-error' : errorLastName }">
<input type="text" name="lastname" id="lastname" placeholder=" " required class="form-control" ng-model="formData.lastname"><br>
<span class="help-block" ng-show="errorLastName">{{ errorLastName }}</span>
</div>
<label> Phone </label><br>
<input type="tel" name="phone" id="phone" maxlength="13" class="form-control" ng-model="formData.phone"><br>
<div id="email-group" class="form-group" ng-class="{ 'has-error' : errorEmail }">
<label> Email *</label><br>
<input type="email" name="c_email" id="c_email" autocomplete="off" required class="form-control" ng-model="formData.c_email"><br>
<span class="help-block" ng-show="errorEmail">{{ errorEmail }}</span>
</div>
<div id="company-group" class="form-group" ng-class="{ 'has-error' : errorCompany }">
<label> Company *</label><br>
<input type="text" name="company" id="company" required class="form-control" ng-model="formData.company"><br>
<span class="help-block" ng-show="errorCompany">{{ errorCompany }}</span>
</div>
<div id="comment-group" class="form-group" ng-class="{ 'has-error' : errorComment }">
<label> Comments *</label><br>
<textarea name="comment" id="comment" required style="height: 200px; width: 350px;" class="form-control" ng-model="formData.comment"></textarea><br>
<span class="help-block" ng-show="errorComment">{{ errorComment }}</span>
<button type="submit" class="btn btn-success btn-lg btn-block">
Submit
</button>
</form>
</div>
</div>
Note:
1- Scope variables of the upper controller works fine. {{subject}} and {{body}}
2- I have Arabic all over the form, but I doubt that has anything to do with it.
3- <input type="hidden" ng-value="CompanyEmail"> works fine when I comment out the <form> tag.
4- I'm using Laravel for my back-end, and the AngularJS App code is in the home.php file within the Laravel Views folder, and my AngularJS Partials Views are in the public folder.
This is exactly my error:
TypeError: undefined is not a function
at toggleValidCss (localhost/money/public/scripts/angularjs/angular.js:16293:14)
at new FormController (localhost/money/public/scripts/angularjs/angular.js:16288:3)
at invoke (localhost/money/public/scripts/angularjs/angular.js:3965:17)
at Object.instantiate (localhost/money/public/scripts/angularjs/angular.js:3976:23)
at $get (http://localhost/money/public/scripts/angularjs/angular.js:7315:28)
at http://localhost/money/public/scripts/angularjs/angular.js:6711:34
at forEach (localhost/money/public/scripts/angularjs/angular.js:332:20)
at nodeLinkFn (localhost/money/public/scripts/angularjs/angular.js:6698:11)
at compositeLinkFn (localhost/money/public/scripts/angularjs/angular.js:6146:13)
at nodeLinkFn (localhost/money/public/scripts/angularjs/angular.js:6746:24) angular.js:10126 (anonymous function)angular.js:7398 $getangular.js:6755 nodeLinkFnangular.js:6146 compositeLinkFnangular.js:6042 publicLinkFnangular.js:6166 $get.boundTranscludeFnangular.js:6773 controllersBoundTranscludeangular-route.js:865 vangular.js:13093 $get.Scope.$broadcastangular-route.js:547 (anonymous function)angular.js:11682 deferred.promise.then.wrappedCallbackangular.js:11682 deferred.promise.then.wrappedCallbackangular.js:11768 (anonymous function)angular.js:12811 $get.Scope.$evalangular.js:12623 $get.Scope.$digestangular.js:12915 $get.Scope.$applyangular.js:8450 doneangular.js:8664 completeRequestangular.js:8603 xhr.onreadystatechange