Validation still saves null fields in DB - angularjs

I'm a newbie to AngularJS. I need to validate the fields so when the user types empty information, the error is shown and data still does not save into DB. If information is valid then ofcourse it must be saved into my DB
The messages works fine, however content still gets saved if the user leaves empty fields and hits submit.
Below is my validation of the controller:
app.controller('addContactCtrl', ['$scope', '$http', function($scope, $http)
{
$scope.newContact = function(contact) {
$scope.queryMsg= ""; //displays if sent or not in html form
//post is used to create
$http.post('model/addContact.php', contact).success(function(data) {
if (data && contact != "")
{//row inserted into table
$scope.queryMsg = "Query has been sent successfully.";
$scope.contact = "";
}
else
{
$scope.queryMsg = "Fields cannot be left empty.";
}
})
};
}
]);
Thanks for your help!

I would validate on the form.
The submit button will be disabled until the form is valid, you can use ng-messages to show a message.
you can read more about it https://scotch.io/tutorials/angularjs-form-validation
<form name="myForm">
<input ng-model="data" required>
<input ng-model="contact" required>
<button ng-disabled myform.$invalid >submit</button>
</form>

You might need to validate it before posting the data. You doing validation after post. Please try this
app.controller('addContactCtrl', ['$scope', '$http', function($scope, $http)
{
$scope.newContact = function(contact) {
$scope.queryMsg= ""; //displays if sent or not in html form
//post is used to create
if (contact != "") {
$http.post('model/addContact.php', contact).success(function(data) {
if (data){
$scope.queryMsg = "Query has been sent successfully.";
}
})
} else {
$scope.queryMsg = "Fields cannot be left empty.";
}
};
}
]);

Related

Ionic View Template Not Being Updated When $scope Variable Is Updated In Controller

I have an ionic app I'm testing the ability to check for fingerprint login. All this works, BUT when I check for whether a user has stored login credentials and get back the decrypted value, I want to SHOW a button that allows user to initiate fingerprint login.
The problem is, when I get back the success when gathering credentials from SecureStorage, I set a variable to show the button ($scope.canUseFingerprint) which is modeled to a button in the view using ng-if. BUT the button never shows up, UNLESS I type a single character into the email input again (there is no "change" function on the input).
I have inspected and it shows the variable is getting set to true, yet the button will not showup until a single character is entered into that email input.
Can someone take a look?
Here is my view:
<form name="loginForm" ng-submit="login(email, password)">
<label>Email</label>
<input type="text" ng-model="email" placeholder="typehere"></input>
<label>Password</label>
<input type="text" ng-model="password" placeholder="typehere"></input>
<button type="submit">Test Login</button>
<!--Below Button Won't Showup-->
<button type="button" ng-if="canUseFingerprint" ng-click="showFingerPrint()">Show Finger Print</button>
<button type="button" ng-click="testShowFingerPrint()">Test Show Button</button>
<button type="button" ng-click="clearKeys()">Clear All Keys</button>
</form>
Here is my controller:
$ionicPlatform.ready(function(){
$scope.canUseFingerprint = false; //Initialized to false
var ss = new cordova.plugins.SecureStorage(
function () {
console.log('Success');
// $scope.allowFingerprintLogin = true;
setTimeout(function(){
checkForLoginCreds(); //Checks for login credentials
},3000)
},
function (error) {
$scope.canUseFingerprint = false;
addLockScreen();
console.log('Error ' + error);
},
'my_app');
var checkForLoginCreds = function(){
ss.get(
function (value) {
console.log('Success, got ' + value);
// This should activate the button, but does nothing. It DOES get set to true. Only after typing single character in input does the button show.
$scope.canUseFingerprint = true;
},
function (error) { console.log('Error ' + error); },
'loginInfo');
}
})
To convert ss.get from a callback-based service to a promise-based service, use the AngularJS $q Service:
function ssGetPromise(ss,key) {
var deferred = $q.defer();
ss.get(
function (value) {
console.log('Success, got ' + value);
deferred.resolve(value);
},
function (error) {
console.log('Error ' + error);
deferred.reject(error);
},
key
);
return deferred.promise;
}
Usage:
ssGetPromise(ss,'loginInfo').then(function(value) {
$scope.canUseFingerprint = true;
});
The $q Service creates promises that are integrated with the AngularJS Framework. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.

While navigating to a page, data is not getting pre-filled

I am getting the data in the controller from firebase database using angularfire api and updating the profile.user object from that data.
Now the problem is After login when I am routing to profile.html page, data is not getting pre-filled for that user in the fields which he had saved earlier in the database.
Thank you.
//The controller code is:
.controller('ProfileController', function($rootScope, $timeout, $location, authObj, fbRef) {
var profile = this;
// Check the current user
var user = authObj.$getAuth();
// If no current user send to register page
if (!user) {
$location.path('/register');
return;
}
var userRef = fbRef.child('users').child(user.uid);
(function init() {
// show the message if User moves to profile page
$rootScope.alertInfo = {
title: 'You are successfully logged in!!',
detail: 'You are still logged in',
className: 'alert alert-success'
};
// Load user info
userRef.once('value', function(snap) {
profile.user = snap.val();
if (!profile.user) {
return;
}
});
})();
profile.updateProfile = function() {
userRef.set(profile.user, function onComplete() {
// show the message if write is successful
$rootScope.alertInfo = {
title: 'Successfully saved!',
detail: 'You are still logged in',
className: 'alert alert-success'
};
});
};
})
Corresponding route for this controller is:
.when('/profile', {
controller:'ProfileController as profile',
templateUrl:'view/profile.html'
})
View for this controller is(profile.html):
<form id="frmProfile" role="form">
<h2>Profile</h2>
<br />
<div class="form-group">
<label for="txtName">Name</label>
<input type="text" ng-model="profile.user.name" class="form-control" id="txtName" placeholder="Name" name="name" />
</div>
<div class="form-group">
<label for="ddlDino">Favorite Dinosaur</label>
<select id="ddlDino" ng-model="profile.user.favoriteDinosaur" name="favoriteDinosaur" class="form-control">
<option>None</option>
<option>Pteranodon</option>
<option>Lambeosaurus</option>
<option>Stegosaurus</option>
<option>Daspletosaurus</option>
</select>
</div>
<button type="submit" ng-click="profile.updateProfile(profile.user)" class="btn btn-primary">Update</button>
FirebaseRef.once is asynchronous and angular has no way of knowing it should digest when the data returns. You need to add $rootScope.$apply() inside the callback to update your program when the data returns. Alternatively, it is recommended to use AngularFire which will handle this type of thing for you.
// Load user info
userRef.once('value', function(snap) {
profile.user = snap.val();
if (!profile.user) {
return;
}
$rootScope.$apply()
});

How to wait for response in angularjs

What I am doing is putting the filter on table (contains records). When I type into search box (used http get method), table data get updated as per search box. But when I type very fast, then I see in console 500 Internal Server error.
The main problem is before comming previous response I am firing the next request.
There is no problem in result. Just console shows every http request. And in case of fast typing in search box it gets red.
What is the solution for it?
you could trottle your search input :
var app = angular.module('app', []);
app.controller('TableController', function($scope, $http, $timeout) {
$http.get('yourTableData.json').then(function(result){
$scope.rows = result.data;
});
$scope.filterText = '';
var temp = '',
filterTextTimeout;
$scope.$watch('searchText', function (val) {
if (filterTextTimeout){
$timeout.cancel(filterTextTimeout);
}
temp = val;
filterTextTimeout = $timeout(function() {
$scope.filterText = temp;
$http.get($scope.filterText).then(function(result){
$scope.rows = result;
}
}, 250);
})
});
<input id="searchInput" type="search" placeholder="search field" ng-model="searchText" />
<div class="record" ng-repeat="row in rows | filter:filterText">
<span>{{row.content}}</span>
</div>

I am not able to pass my recent values added in service method to html page

This is my first html page where I need to populate my recently added data:
<div>
<!--I have binded busdomain through controller -->
<swt-tree tree-data="busdomain"</swt-tree>
</div>
This is my child html page which is called under first page and I want to pass the values entered on this page to my parent page. But not getting recent values until I reload the page.
<span ng-show="true"</span>Name</label>
<div class="col-sm-9">
<input focus="" id="name" placeholder="Name" ng-model="busdomain.name" ng-change="domainNameChanged()" required="true">
</div>
<button type="submit" ng-click="addSubTree(createdomain.$valid)" id="btnData">OK</button>
This is my controller, I have called service through controller:
controller('domainController', ['$scope', '$state', 'DomainNameService', function($scope, $state, DomainNameService) {
$scope.activeTab = 1;
$scope.currentBDStatement=[];
$scope.statements=[];
$scope.childBD =[];
$scope.busdomain=[];
<!--It is used when I navigate from parent to child for the first time -->
$scope.busdomain = DomainNameService.getBusDomainName();
$scope.addSubTree = function(val){
//Done some code here
//In $scope.statements I am getting the values which I need to pass on html page
//I am setting the value in service which I got from my child html page
DomainNameService.setBusDomain($scope.statements);
//Here I am calling the get method of my service and able to get the values which i have set.
$scope.busdomain = DomainNameService.getBusDomainName();
//Redirecting to my parent page here I want to show the values which i have set in $scope.busdomain but I am not getting recent added values..
$state.go('BusDomainTree');
}
This is my service.js:
Here I have used getter and setter:
app.factory('DomainNameService', function() {
var busDomain = undefined;
var busDomainValue=[];
setBusDomain:function(busDomName){
this.busDomainValue=busDomName;
},
getBusDomainName: function(){
<!--I am getting the values here which I need to pass to html page -->
return this.busDomainValue;
}
})
Full controller code:
controller('domainController', ['$scope', '$state', 'DomainNameService', function($scope, $state, DomainNameService) {
$scope.activeTab = 1;
$scope.currentDomain = {};
$scope.currentBDStatement=[];
$scope.statements=[];
$scope.childBD =[];
var statementTree = {};
$scope.busdomain=[];
$scope.domain = DomainNameService.getDomainName();//Getting parent name here
$scope.busdomain = DomainNameService.getBusDomainName();
//$scope.busDom = DomainNameService.getBusDomainModel($scope.statements);
$scope.addTree = function(isValid) {
if(isValid) {
var stType = $scope.domain.name;//Getting value from html page of parent
$scope.currentDomain = $scope.getNewDomain(stType,varType);
$scope.statements.push($scope.currentDomain);
//Adding parent name to tree code $scope.statementTree.setNewInput($scope.statements);
$scope.isAdd = false;
DomainNameService.addDomain($scope.domain.name);
$scope.domain.domainName = DomainNameService.getDomainName()[0];
$state.go('DomainTree');
}
}
$scope.getNewDomain = function(stType,varType) {
//passing parent name as json
return {domainNode:[{name:stType}],name:stType, varName:varType};
}
$scope.addbusinessDomain = function() {
$state.go('DomainTree.businessDomain');
}
//This method is called for child
$scope.addSubTree = function(val){
var varType = "busDomain";
var domain=[];
var busDomainName=$scope.busdomain.name;
var parent = DomainNameService.getDomainName()[0];
DomainNameService.addChildBD(busDomainName);
$scope.childBD=DomainNameService.getChildBD();
$scope.currentStatement = $scope.busdomain.name;
$scope.currentBDStatement.push($scope.busdomain.name); $scope.currentDomainName=$scope.getBusDomain($scope.childBD,parent,varType);
$scope.statements.push($scope.currentDomainName);
$scope.statementTree.setNewInput($scope.statements);
DomainNameService.setBusDomain($scope.statements);
$scope.busdomain = DomainNameService.getBusDomainName();
$state.go('BusDomainTree');
}
$scope.getBusDomain = function(stType,parent,varType) {
return {node:[{name:parent}],name:parent, childNode:stType, refType: varType};
}
I am able to fetch values from service but I am not able to populate the recently added value to html page. For that I need to reload the page. Please some one help me out in resolving this issue. Thanks in advance

When page refresh, how to call back function in angularjs

I'm trying to maintain session after page refresh in angularjs using java. I have seen many examples but, i didn't find proper solution which exactly I'm looking for.
Please find below login snippet code, when i click on login button it is calling loginUser()function in LoginController
When i do page refresh it is going to LoginController but it is not going inside loginUser()function.
According to my knowledge until we call function, it doesn't goes inside of it.
When I do refresh how can i call back loginUser() function.
please help me out from these. Appreciated..Many thanks.
LoginController.js
function LoginController($scope, $http, $location, $rootScope,
userService, SessionIdService) {
$scope.user = {};
$scope.user.username = '';
$scope.user.password = '';
$rootScope.loginUser = function(username, password) {
$scope.resetError();
$http.post('/user/main/login/' + username, password).success(
function(login) {
if (login.sessionId === null) {
$scope.setError(login.status);
return;
} else {
$rootScope.userlogin = login.uname;
userService.setUserName(login.uname);
SessionIdService.setSessionId(login.sessionId);
$location.path("/home");
}
}).error(function() {
$scope.setError('Invalid user/password combination');
});
};
$scope.resetError = function() {
$scope.error = false;
$scope.errorMessage = '';
};
$scope.setError = function(message) {
$scope.error = true;
$scope.errorMessage = message;
$rootScope.sees = '';
$rootScope.userlogin = '';
};
};
app.js
app.run(function($rootScope, $location, SessionIdService) {
$rootScope.$on("$routeChangeStart", function(event, next, current) {
console.log("Routechanged... ");
if (SessionIdService.getSessionId == "true") {
if (next.templateUrl == "scripts/views/homescreen.html") {
$location.path("/home");
} else {
$location.path("/screen");
}
}
});
});
login.html
<input name="textfield" type="text" ng-model="user.username"/>
<input name="textfield" type="password" ng-model="user.password"/>
<button type="button" ng-lick="loginUser(user.username,user.password)">Login</button>
It is not clear to me why you want to call loginUser after page refresh. Isn't the user already logged in? I think what you want is to call the success function inside the loginIser. In that case, you need to embed that data as a global JS variable inside your Java template, and pass that to your controller somehow.
You probably want these to be run after refresh:
$rootScope.userlogin = login.uname;
userService.setUserName(login.uname);
SessionIdService.setSessionId(login.sessionId);
$location.path("/home");
So, in your Java template, do something like:
<script>window.UNAME = {% this comes from your database %};window.SESSIONID={% similar %}</script>
Then, call that function somehow with window.UNAME as input. (or in your controller, check for the existence of window.UNAME and call it immediately. Something like:
window.UNAME && function (name, sessionId) {
$rootScope.userlogin = uname;
userService.setUserName(uname);
SessionIdService.setSessionId(sessionId);
$location.path("/home");
) {
}(window.UNAME, window.SESSION_ID)
Some other recommendations (unrelated to your main problem probably):
First of, change $rootScope.loginUser = function(username, password) { to
$rootScope.loginUser = function() {
var username = $scope.user.username;
var password = $scope.user.password
since you already have access to username and password there. So, change ng-click="loginUser()".
Second, SessionIdService.getSessionId == "true" seems off, check should probably be just SessionIdService.getSessionId

Resources