Returning data from POST using KnockoutJS + DurandalJS - javascript

I've been working on this for too long.... And since jsfiddle doesn't support Durandal was hoping someone could shine some light on where the problem is. I am leaning towards my data bindings.
HTML:
<section>
<div class="row row-centered">
<div class="col-sm-6 col-sm-4 col-sm2 col-centered">
<div class="panel panel-info">
<div class="panel-heading">
Contact
</div>
<div class="panel-body">
<form role="form">
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" data-bind="value: name, valueUpdate: 'afterkeydown'" placeholder="Username">
</div>
<div class="form-group">
<label for="inputEmail">E-mail</label>
<input type="email" class="form-control" id="inputEmail" data-bind="value: email, valueUpdate: 'afterkeydown'" placeholder="Email">
</div>
<div class="form-group">
<label for="inputText">Message</label>
<textarea class="form-control" id="inputText" data-bind="value: msg, valueUpdate: 'afterkeydown'" placeholder="Message"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-info" data-bind="click:sendEmail, enable: name, enable: email, enable: msg">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- ko if: debugTrue -->
<div class="row row-centered">
<div class="col-sm-6 col-sm-4 col-sm2 col-centered">
<div class="panel panel-success">
<div class="panel-heading">
Data Return
</div>
<div class="panel-body">
<ul data-bind="foreach: debugInfo(), as: 'd'">
<li data-bind="html: d"></li>
</ul>
</div>
</div>
</div>
</div>
<!-- /ko -->
</section>
Durandal:
define(function (require) {
var app = require('durandal/app'),
http = require('plugins/http'),
ko = require('knockout');
var url = '/api/api.php';
return {
name: ko.observable(),
email: ko.observable(),
msg: ko.observable(),
debugInfo: ko.observableArray([]),
sendEmail: function() {
var qs = {
method: 'email',
name: this.name(),
to: this.email(),
msg: this.msg(),
};
var that = this;
app.showMessage('Email sent to ' + this.name() + ' at ' + this.email());
return http.post(url, qs).then(function(response) {
that.debugInfo(response.items);
});
}
};
});
Returned from api.php:
{"images":1,"items":[1,2,3,4],"status":1}
So the problem is that when iterating through debugInfo() it is not populating.
ANy help appreciated.

There are a few problems with what you have so far.
var that = this; is in the wrong spot. this appears to represent the sendmail function and as such there is no debugInfo property associated with it.
You have a <!-- ko if: debugTrue --> knockout virtual element. there is no corresponding debugTrue property on the viewmodel.
the binding that you need to use the foreach with an as: d is as follows
<ul data-bind="foreach: {data: debugInfo, as: 'd'}">
<li data-bind="html: d"></li>
</ul>
Here is a jsFiddle Demo then will hopefully help

Related

Error: [ng:areq] Argument 'UsersSettingsController' is not a function, got undefined

I'm trying to create a edit profile section in angularjs. For that i create in my users controller a section to make a rest api call to get info to inject on the page and later i will do the parte of changePassword also.
At the moment i'm getting the error "Error: [ng:areq] Argument 'UsersSettingsController' is not a function, got undefined" and I cant undestand why.
editAccount view:
<div class="row" ng-controller="UsersSettingsController as usersSettingsCtrl" >
{{userInfo}}
<!-- edit form column -->
<div class="col-md-9 personal-info">
<h3>Personal info</h3>
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="col-md-3 control-label">Username:</label>
<div class="col-md-8">
<input class="form-control" type="text" style="background-color: #fff" value="{{userInfo.username}}" readonly>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Organization:</label>
<div class="col-lg-8">
<input class="form-control" type="text" style="background-color: #fff" value="{{userInfo.organization_name}}" readonly>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Permission Group:</label>
<div class="col-lg-8">
<input class="form-control" type="text" style="background-color: #fff" value="{{userInfo.permission_group_name}}" readonly>
</div>
</div>
<div class="form-group" nf-ig="user.organization_permission_group_id=='df0417e3-ce36-41ca-9f13-f58c1a3a96f5'">
<label class="col-lg-3 control-label">Root:</label>
<div class="col-lg-8">
<input class="form-control" type="text" style="background-color: #fff" value="{{userInfo.data.root}}" readonly>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email:</label>
<div class="col-lg-8">
<input class="form-control" type="text" style="background-color: #fff" value="{{userInfo.username}}" readonly>
</div>
</div>
<hr>
<h4>Change Password</h4>
<br>
<form name="newPasswordForm" role="form" ng-submit="newPasswordForm.$valid && ok()" novalidate>
<div class="form-group">
<label class="col-md-3 control-label">Change Password:</label>
<div class="col-md-8">
<input type="password" name="newPassword" ng-model="password.new"
ng-minlength="6" required />
<span class="help-block"
ng-show="newPasswordForm.newPassword.$dirty && newPasswordForm.newPassword.$invalid">
Please enter a new password, it must be at least 6 characters long.
</span>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Confirm password:</label>
<div class="col-md-8">
<input type="password" name="newPasswordConfirm"
ng-model="password.confirm" ng-minlength="6"
value-matches="password.new" required />
<span class="help-block"
ng-show="newPasswordForm.newPasswordConfirm.$dirty && newPasswordForm.newPasswordConfirm.$invalid">
Please enter the same password again to confirm.
</span>
</div>
</div>
</form>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input type="button" class="btn btn-primary" style="float:right" value="Save Changes">
<div ng-messages="registrationForm.confirmPassword.$error" ng-messages-include="messages.html"></div>
</div>
</div>
</form>
</div>
</div>
usersController:
app.controller('UsersSettingsController',['$scope', 'user', function ($scope, user) {
$http.get('/api/users/userInfo/'+user.id).success(function (data) {
console.log("user info ",data);
$scope.userInfo = data;
});
//changePassword call to rest api
}]);
usersDirective:
(function() {
var app = angular.module('userSettings', []);
app.directive('valueMatches', ['$parse', function ($parse) {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ngModel) {
var originalModel = $parse(attrs.valueMatches),
secondModel = $parse(attrs.ngModel);
// Watch for changes to this input
scope.$watch(attrs.ngModel, function (newValue) {
ngModel.$setValidity(attrs.name, newValue === originalModel(scope));
});
// Watch for changes to the value-matches model's value
scope.$watch(attrs.valueMatches, function (newValue) {
ngModel.$setValidity(attrs.name, newValue === secondModel(scope));
});
}
};
}]);
})();

Bootstrap 4 Form Validation

I'm a beginner with bootstrap and I have seen a lot of bootstrap 3 form validation plugins etc, but I haven't found any for bootstrap 4.
I'm trying to validate multiple forms, and here is my code:
<!-- Contact -->
<div class="container white">
<div class="row">
<div class="container white percent100">
<div class="col-lg-12">
<div class="padder-t2">
<h1>Contact</h1>
<div class="horiz-divider"></div>
</div>
</div>
</div>
</div>
<div class="row padder-t padder-b">
<div class="container white">
<div class="col-lg-12">
<!-- Form -->
<form class="form-horizontal" action=" " method="post" id="contact_form">
<fieldset>
<!-- Text input-->
<div class="form-group">
<div class="row">
<div class="col-md-4 col-lg-4">
<label class="control-label pull-right"><h4>First Name</h4></label>
</div>
<div class="col-md-4 col-lg-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
<input id="firstname" name="firstname" placeholder="First Name" class="form-control" type="text">
</div>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<div class="row">
<div class="col-md-4 col-lg-4">
<label class="control-label pull-right"><h4>Last Name</h4></label>
</div>
<div class="col-md-4 col-lg-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
<input id="lastname" name="lastname" placeholder="Last Name" class="form-control" type="text">
</div>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<div class="row">
<div class="col-md-4 col-lg-4">
<label class="control-label pull-right"><h4>E-Mail</h4></label>
</div>
<div class="col-md-4 col-lg-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input id="email" name="email" placeholder="E-Mail Address" class="form-control" type="email">
</div>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<div class="row">
<div class="col-md-4 col-lg-4">
<label class="control-label pull-right"><h4>Phone #</h4></label>
</div>
<div class="col-md-4 col-lg-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-phone"></i></span>
<input id="phone" name="phone" placeholder="Phone" class="form-control" type="text">
</div>
</div>
</div>
</div>
<!-- Text area -->
<div class="form-group">
<div class="row">
<div class="col-md-4 col-lg-4">
<label class="control-label pull-right"><h4>Message</h4></label>
</div>
<div class="col-md-4 col-lg-5 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-pencil"></i></span>
<textarea id="comment" class="form-control" name="comment" placeholder="Your Message"></textarea>
</div>
</div>
</div>
</div>
<!-- Success message -->
<div class="alert alert-success" role="alert" id="success_message">Success <i class="fa fa-thumbs-up"></i> Thanks for contacting us, we will get back to you shortly.</div>
<!-- Button -->
<div class="form-group">
<div class="row">
<label class="col-md-4 col-lg-4 control-label"></label>
<div class="col-md-4 col-lg-4">
<button type="submit" class="btn btn-danger raised">Send <i class="fa fa-paper-plane"></i></button>
</div>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<div class="row padder-b">
<div class="row col-lg-12">
<div class="col-md-3 col-lg-3"></div>
<h4 class="col-md-9 col-lg-9">Contact us directly:</h4>
</div>
<div class="row col-lg-12">
<div class="col-md-3 col-lg-3"></div>
<h4 class="col-md-2 col-lg-2 padder-lr">Mail:</h4>
<a class="col-md-6 col-lg-6 padder-lr" href="mailto:lorem#ipsum.com">
<h4 id="mail">lorem#ipsum.com</h4>
</a>
</div>
<div class="row col-lg-12">
<div class="col-md-3 col-lg-3"></div>
<h4 class="col-md-2 col-lg-2 padder-lr">Adress:</h4>
<h4 class="col-md-6 col-lg-6 padder-lr" id="adress">2 LoremIpsum Road, 67000 City - Country</h4>
</div>
</div>
</div>
I have tried to modify existing js, but I had no luck.
Here is the rendered form:
jsfiddle of the form
First I solved my issue with an external library like Jonathan Dion suggested. But recently I came across this :
Bootstrap v4.0 introduced their own form validation that you can still pair with backend php validation. From the Doc :
<form class="needs-validation" novalidate>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustom01">First name</label>
<input type="text" class="form-control" id="validationCustom01" placeholder="First name" value="Mark" required>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback">
Doesn't look good!
</div>
</div>
</div>
</div>
Then using JS :
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
This provides input border colorating and displays the valid / invalid feedback blocks according to the given pattern or properties. It is applied via CSS’s two pseudo-classes, :invalid and :valid. It applies to <input>, <select>, and <textarea> elements.
Update 2020 - Bootstrap 4.4.x
Here's another option (modern JS) if you want to validate each input one at a time (live or real-time) instead of waiting for the entire form to be submitted...
(function() {
'use strict';
window.addEventListener('load', function() {
// fetch all the forms we want to apply custom style
var inputs = document.getElementsByClassName('form-control')
// loop over each input and watch blur event
var validation = Array.prototype.filter.call(inputs, function(input) {
input.addEventListener('blur', function(event) {
// reset
input.classList.remove('is-invalid')
input.classList.remove('is-valid')
if (input.checkValidity() === false) {
input.classList.add('is-invalid')
}
else {
input.classList.add('is-valid')
}
}, false);
});
}, false);
})()
<form class="container" novalidate="" action="/echo" method="POST" id="myForm">
<div class="form-group">
<label class="form-control-label" for="input1">Enter some input</label>
<input type="text" class="form-control" name="input1" id="input1"
autocomplete="no" required>
<div class="valid-feedback">Success! You've done it.</div>
<div class="invalid-feedback">No, you missed this one.</div>
</div>
<div class="form-group">
<label class="form-control-label" for="input2">Enter password</label>
<input type="text" class="form-control"
pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}$"
autocomplete="no" name="input2" id="input2">
<div class="valid-feedback">Nice! You got this one!</div>
<div class="invalid-feedback">At least 6 chars: 1 uppercase, 1 lowercase and numeric</div>
</div>
<div>
<button type="submit" class="btn btn-secondary" id="btnSubmit">Submit</button>
</div>
</form>
https://codeply.com/p/mzBNbAlOvQ
You can use any library available on the web. You may try jqueryvalidation. It's pretty easy to use, just read the documentation.
Add the required attribute on your input and jqueryvalidation will do the job. For styling, you can add your own CSS and make it look like bootstrap.
Hopes it help
$(document).ready(function(){
$('#contact_form').validate()
})
Demo
I found a simpler and a bit more modern way to implement Bootstrap 4 JS Form validation:
Note: Keep in mind that each <form> element must have the novalidate attribute and at the same time, each <input> element in it must have the required attribute.
// Upon load..
window.addEventListener('load', () => {
// Grab all the forms
var forms = document.getElementsByClassName('needs-validation');
// Iterate over each one
for (let form of forms) {
// Add a 'submit' event listener on each one
form.addEventListener('submit', (evt) => {
// check if the form input elements have the 'required' attribute
if (!form.checkValidity()) {
evt.preventDefault();
evt.stopPropagation();
console.log('Bootstrap will handle incomplete form fields');
} else {
// Since form is now valid, prevent default behavior..
evt.preventDefault();
console.info('All form fields are now valid...');
}
form.classList.add('was-validated');
});
}
});
<!-- Load necessary libraries -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<!-- Add form -->
<div class="container" style="padding-top: 40px;">
<form class="student-search needs-validation" novalidate>
<div class="form-row">
<div class="form-group col-6">
<label for="input-name-search" class="sr-only">Name</label>
<input type="text" class="form-control" id="input-name-search" placeholder="Name" required>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Enter a name please.</div>
</div>
<div class="col-6">
<button id="btn-search" type="submit" class="btn btn-success btn-block">Search student</button>
</div>
</div>
</form>
</div>
I just figured out the reason my code wasn't validating: I didn't have a submit button to trigger the validation. Make sure to have it.
<button type="submit" class="btn btn-primary">Save</button>
There's no real need for a library here, you can use the native reportValidation() method: MDN. You can call it on individual inputs or on the entire form itself.

How do I clear or reset data in a form in angularjs?

Been finding how to clear form data with the use of angular and $setPristine Function but still no results always gives me an error saying $setPristine is not a function. Can anyone kindly help me for a solution?
here's my angular.controller
$scope.AddCustomer = function () {
var CustDetails = {
cname: $scope.CusDetails.cname,
comname: $scope.CusDetails.comname,
tel: $scope.CusDetails.tel,
email: $scope.CusDetails.email
};
CustService.Customer(CustDetails, function (res) {
console.log(res);
$.extend($.gritter.options, {
position: 'bottom-right',
});
if (res.data == 'success') {
$.gritter.add({
title: 'Success!',
text: 'Successfully added the new customer ' + '<h4><span class="label label-primary">' + CustDetails.cname + '</span></h4>',
time: '5000',
close_icon: 'l-arrows-remove s16',
icon: 'glyphicon glyphicon-ok-circle',
class_name: 'success-notice'
});
//CustDetails = {};
customerForm.$setPristine(true);
}
else {
$.gritter.add({
title: 'Failed!',
text: 'Failed to add a new customer',
time: '5000',
close_icon: 'l-arrows-remove s16',
icon: 'glyphicon glyphicon-remove-circle',
class_name: 'error-notice'
});
}
});
}
Here's the Html code
<div ng-controller="AddCustomerController">
<div class="page-content-wrapper">
<div class="page-content-inner">
<div id="page-header" class="clearfix">
<div class="page-header">
<h2>Add Customer</h2>
<span class="txt">Create and add new customer.</span>
</div>
</div>
<!--Start .row-->
<div class="row">
<div class="col-md-1">
</div>
<div class="col-lg-9 col-sm-9 col-xs-12">
<!--col-lg-9 starts here-->
<div class="panel panel-default toggle panelMove panelClose panelRefresh">
<div class="panel-heading">
<h4 class="panel-title">Customer Details</h4>
</div>
<div class="panel-body pt0 pb0">
<form class="form-horizontal group-border stripped" id="customerForm">
<div class="form-group">
<label class="col-lg-2 col-md-3 control-label">Customer Name</label>
<div class="col-lg-10 col-md-9">
<input type="text" required id="cname" ng-model="CusDetails.cname" class="form-control" name="cname" />
</div>
</div>
<!--end of .form-group-->
<div class="form-group">
<label class="col-lg-2 col-md-3 control-label">Company Name</label>
<div class="col-lg-10 col-md-9">
<input type="text" required id="comname" ng-model="CusDetails.comname" class="form-control" name="comname" />
</div>
</div>
<!--end of .form-group-->
<div class="form-group">
<label class="col-lg-2 col-md-3 control-label" for="">Telephone Number</label>
<div class="col-lg-10 col-md-9">
<div class="input-group input-icon">
<span class="input-group-addon"><i class="fa fa-phone s16"></i></span>
<input ng-model="CusDetails.tel" class="form-control" id="ctel" type="text" placeholder="(999) 999-9999">
</div>
</div>
</div>
<!-- End .form-group -->
<div class="form-group">
<label class="col-lg-2 col-md-3 control-label" for="">Email address</label>
<div class="col-lg-10 col-md-9">
<input id="email" ng-model="CusDetails.email" type="text" class="form-control" name="placeholder" placeholder="someone#example.com">
</div>
</div>
<!-- End .form-group -->
</form>
</div>
</div>
<!--End .panel-->
</div>
<!--.col-9 ends here-->
</div>
<!--End .row-->
<!--Start .row-->
<div class="row">
<div class="col-md-1"></div>
<div class="col-lg-9 col-sm-9 col-xs-12">
<button id="btnSubmit" type="submit" ng-click="AddCustomer()" class="btn btn-info pad"><span class="fa fa-user-plus"></span> Add Customer</button>
<button type="submit" class="btn btn-default pad">Cancel</button>
</div>
</div>
</diV>
</div>
</div>
You can remove form field value by removing value of ng-model like
Your code
var CustDetails = {
cname: $scope.CusDetails.cname,
comname: $scope.CusDetails.comname,
tel: $scope.CusDetails.tel,
email: $scope.CusDetails.email
};
Replace with this
$scope.CustDetails = {
cname: $scope.CusDetails.cname,
comname: $scope.CusDetails.comname,
tel: $scope.CusDetails.tel,
email: $scope.CusDetails.email
};
Your code
customerForm.$setPristine(true);
Replace with this
$scope.CustDetails={};
use:
$scope.$destroy
as it removes all the children associated to the parent scope and will clear all the data associated with it.
Use
$scope.customerForm.$setPristine(true);
Give the form a name like
name= "CusDetails"
Then It will solve the problem.
Use name attr instead of id. name="forName"
The form reference inside Controller will be $scope.formName
You can set the form with the code below:
$scope.customerForm.$setPristine();
$scope.customerForm.$setUntouched();
$scope.CustDetails={};

How to change view in Knockout JS

i have a short question. I am using Knockout JS and having this view and ViewModel:
var LoginViewModel = function () {
var self = this;
self.userName = ko.observable();
self.userPassword = ko.observable();
self.signin = function () {
data = ko.toJSON(self);
$.ajax({
url: "/signin",
type: "post",
data: ko.toJSON(self),
contentType: "application/json",
success: function (data, textStatus, xhr) {
alert(xhr.status);
// If status == 200(OK) change view
},
error: function (jqXHR, textStatus, errorThrown) {
alert("failure");
}
});
}
}
ko.applyBindings(new LoginViewModel());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<div class="container">
<div class="col-md-4 col-md-offset-4" data-bind="visible: isVisible">
<div class="panel panel-default">
<div class="panel-heading" style="text-align: center;">
<strong class="">SEHA</strong>
</div>
<div class="panel-body">
<form class="form-horizontal">
<div class="form-group">
<label for="username" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input class="form-control" required="" type="text" data-bind="value: userName">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-3 control-label">Password</label>
<div class="col-sm-9">
<input class="form-control" required="" type="password" data-bind="value: userPassword">
</div>
</div>
<div class="form-group last">
<div class="col-sm-offset-3 col-sm-9">
<button class="btn btn-success btn-sm" data-bind="click: signin">Sign in</button>
</div>
</div>
</form>
</div>
<div class="panel-footer">
~
</div>
</div>
</div>
</div>
I want now to change the "view" if the user logs in. How can i accomplish that?
I also would to like to select a new view model for the next view. How would i do that?
That are my first steps with javascript / knockout, so please be kind.
If you handle the Server part of your application, you might want to return a Redirect Code 301 and specifying the URL to redirect.
Else, you can handle this Client Side, with the javascript code:
window.location.replace("./Home.html");

Clear the form after submit angularjs

hi i want to clear the form values after successfull completion. Houw should i implemnt
<div ng-controller="employeelistController as listControl">
<div class="container form-group" ng-controller="addEmployee as addemp">
<form name="frmEmployee" ng-submit="Add(addemp.employee) && frmEmpbloyee.$valid">
<div class="col-lg-4 ctrmain">
<div class="row">
<div class="col-lg-6">
<strong>Employee No</strong>
</div>
<div class="col-lg-6">
<input type="number" id="txtEmpId" ng-model="addemp.employee.employeeid" required class="form-control" />
</div>
</div>
<div class="row">
<div class="col-lg-6">
<strong>FirstName</strong>
</div>
<div class="col-lg-6">
<input type="text" id="txtfirstName" ng-model="addemp.employee.firstname" required class="form-control" />
</div>
</div>
<div class="row">
<div class="col-lg-6">
<strong>LastName</strong>
</div>
<div class="col-lg-6">
<input type="text" id="txtlastName" ng-model="addemp.employee.lastname" required class="form-control" />
</div>
</div>
<div class="row">
<div class="col-lg-6">
<strong>Department</strong>
</div>
<div class="col-lg-6">
<input type="text" id="txtDept" ng-model="addemp.employee.department" required class="form-control" />
</div>
</div>
<div class="row">
<div class="col-lg-6">
<strong>DOB</strong>
</div>
<div class="col-lg-6">
<input type="date" id="DTdob" ng-model="addemp.employee.dateofbirth" required class="form-control" />
</div>
</div>
<div class="row">
<input type="submit" id="btnSubmit" class="btn btn-primary value=" save" />
</div>
</div>
which is the best way to implement this. I have tried many ways. please help.
$scope.Add = function (emp,$scope) {
this.EmployeeObject = angular.copy(emp);
employee.push(this.EmployeeObject);
$scope.emp = null;
}
which is the best way to implement this. I have tried many ways. please help.
First of all you don't need $scope in the argument of the Add function.
$scope.Add = function (emp) {
this.EmployeeObject = angular.copy(emp);
employees.push(this.EmployeeObject);
this.employee=null;
$scope.$setPristine(true);
}
update it with the demo
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $compile) {
'use strict';
$scope.empList = [];
$scope.addemp = {};
$scope.saveEmp = function(){
$scope.empList.push($scope.addemp);
$scope.reset();
};
$scope.reset = function() {
$scope.addemp = {};
$scope.form.$setPristine();
}
});
input.ng-invalid.ng-dirty {
background-color: #FA787E;
}
input.ng-valid.ng-dirty {
background-color: #78FA89;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MainCtrl">
<form name="form" id="form" novalidate ng-submit="saveEmp()">
<div class="row">
<div class="col-lg-6">
<strong>Employee No</strong>
</div>
<div class="col-lg-6">
<input type="number" id="txtEmpId" ng-model="addemp.employeeid" required class="form-control" />
</div>
</div>
<div class="row">
<div class="col-lg-6">
<strong>FirstName</strong>
</div>
<div class="col-lg-6">
<input type="text" id="txtfirstName" ng-model="addemp.firstname" required class="form-control" />
</div>
</div>
<div class="row">
<div class="col-lg-6">
<strong>LastName</strong>
</div>
<div class="col-lg-6">
<input type="text" id="txtlastName" ng-model="addemp.lastname" required class="form-control" />
</div>
</div>
<div class="row">
<div class="col-lg-6">
<strong>Department</strong>
</div>
<div class="col-lg-6">
<input type="text" id="txtDept" ng-model="addemp.department" required class="form-control" />
</div>
</div>
<div class="row">
<div class="col-lg-6">
<strong>DOB</strong>
</div>
<div class="col-lg-6">
<input type="date" id="DTdob" ng-model="addemp.dateofbirth" required class="form-control" />
</div>
</div>
<div class="row">
<button type="submit" ng-disabled="form.$invalid ">submit</button>
<button type="reset" ng-disabled="form.$pristine" ng-click="reset()">reset</button>
</div>
</form>
<p>form: {{addemp | json}}</p>
<p>empList: {{empList | json}}</p>
<p>Pristine: {{form.$pristine}}</p>
<p> <pre>Errors: {{form.$error | json}}</pre>
</p>
</div></div>
$scope.Add = function (emp) {
this.EmployeeObject = angular.copy(emp);
employee.push(this.EmployeeObject);
$scope.emp = {}; // initialize the form to empty object
$scope.frmEmployee.$setPristine(); // set it to as user has not interacted with the form.
}
I have cleared textbox with below code. e.g I have cleared FirstName textbox.
HTML SECTION
<td ng-show="a">
<input type="text" ng-model="e.FirstName" />
</td>
Controller SECTION
e.FirstName= "";
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $compile) {
'use strict';
function resetform() {
document.getElementById("frmEmployee").reset();
}
$scope.Add = function (emp,$scope) {
this.EmployeeObject = angular.copy(emp);
employee.push(this.EmployeeObject);
resetform();
}
});
Its pure JavaScript with simple one line code.
document.getElementById('yourFormId').reset()
Add this syntax at the end of the function in controller after submitting the form.

Categories

Resources