<< BACK
Directory Structure :
refer link : https://scotch.io/tutorials/angularjs-best-practices-directory-structure
---------------------------------------------------------------------------------------------
Set module and route :
app.js
var app = angular.module('myModule', ['ngRoute', 'ui.bootstrap', '720kb.datepicker','ngIdle','ngCookies']);
app.config(['$routeProvider','KeepaliveProvider', 'IdleProvider','$locationProvider',function($routeProvider,KeepaliveProvider,IdleProvider,$locationProvider){
$routeProvider
.otherwise('/home',{
templateUrl:'components/home/homeView.html',
controller:'homeController'
})
.when('/home',{
templateUrl:'components/home/homeView.html',
controller:'homeController'
})
.when('/login',{
templateUrl:'components/login/loginView.html',
controller:'loginController'
});
}]);
use js :
https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular.min.js
https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular-route.min.js
---------------------------------------------------------------------------------------------
homeController.js :
app.controller("homeController",,['$rootScope','$scope','LocalService','$cookies','$window','MY_CONFIG','$location','$route','$http',function($rootScope,$scope,LocalService,$cookies,$window,MY_CONFIG,$location,$route,$http){
//check cookie values - if value is empty then redirect to login url
var favoriteCookie = $cookies.get('clientToken');
if(favoriteCookie == undefined){
$window.location = MY_CONFIG.baseUrl+'#/login';
}
$scope.collectionAPI = false; //function load only one
$scope.callFunctionByHttp = function(){
if(!$scope.collectionAPI){
$scope.loading = true;
$http({
method: 'POST',
headers: {
clientToken: favoriteCookie
},
url: MY_CONFIG.apiBaseUrl + 'loadDataFunctionName'
}).then(function successCallback(response) {
$scope.collectionData = response.data.data;
$scope.collectionList = response.data.data.collectionListDate;
$scope.collectionAPI = !$scope.collectionAPI;
$scope.loading = false;
}, function errorCallback(response) {
});
};
$scope.newAPI = false;
$scope.callFunctionTo = function(){
if(!$scope.newAPI){
$scope.loading = true;
LocalService.post(MY_CONFIG.apiBaseUrl + 'loadDataFunctionName').then(function(response){
$scope.newData = response.data;
$scope.newList = response.data.newDataListDate;
$scope.newAPI = !$scope.newAPI;
$scope.loading = false;
});
}
};
}]);
---------------------------------------------------------------------------------------------
loginController.js :
app.controller("loginController",['$scope','LocalService','$cookies','$window','MY_CONFIG','$http','$location', function($scope,LocalService,$cookies,$window,MY_CONFIG,$http,$location){
$scope.title ='Login View';
$scope.username = 'admin';
$scope.password = 'admin@123';
$scope.userLogin = function(){
$http({
method: 'POST',
url: MY_CONFIG.apiBaseUrl+'Login',
headers: {
'Authorization' : 'Basic ' + Base64.encode($scope.username+':'+$scope.password)
}
}).then(function(response){
$cookies.put('clientToken', response.data.data.clientToken);
$window.location = MY_CONFIG.baseUrl+'#/home';
});
};
}]);
---------------------------------------------------------------------------------------------
Post form data to controller :
View :
<form name="userForm" ng-submit="customerSearch()">
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-6 marginb15">
<input type="text" ng-required='!txtPolicyNo' maxlength="10" numeric-only class="input-field" ng-model="txtMobileNo" name="txtMobileNo" placeholder="Mobile Number*" />
</div>
<div class="col-md-6 col-sm-6 col-xs-6 marginb15 relative">
<input type="text" ng-required='!txtMobileNo' class="input-field" ng-model="txtPolicyNo" name="txtPolicyNo" placeholder="Policy Number*" />
<span class="addor">OR</span>
</div>
<p ng-show='userForm.txtPolicyNo.$error.required && userForm.txtPolicyNo.$dirty || userForm.txtMobileNo.$error.required && userForm.txtMobileNo.$dirty'>
Mobile Number OR Policy Number Required
</p>
<div class="col-md-6 col-sm-6 col-xs-6 marginb15">
<input type="text" required class="input-field" ng-model="txtDOB" name="txtDOB" placeholder="Date of Birth* (17/June/1988)" />
<span ng-show="userForm.txtDOB.$invalid && userForm.txtDOB.$dirty">
Please Select DOB
</span>
</div>
<div class="col-md-6 col-sm-6 col-xs-6 marginb15 searchbx">
<button type="submit" class="commonbtn" ng-disabled="userForm.$invalid" >Submit</button>
</div>
</div>
</form>
app.js
$scope.customerSearch = function(){
$scope.quickCustomerSearch = {
'mobileNo':$scope.txtMobileNo,
'policyNo':$scope.txtPolicyNo,
'DOB':$scope.txtDOB
};
$http({
method : 'POST',
url : MY_CONFIG.apiBaseUrl + "saveData",
data : $scope.quickCustomerSearch, //forms user object
headers : {'Content-Type':'application/json; charset=utf-8','clientToken': favoriteCookie}
})
.success(function(response) {
$rootScope.policySummary = response.data;
var policySummary = JSON.stringify($rootScope.policySummary);
$window.localStorage.setItem("policySummary",policySummary);
$window.location = MY_CONFIG.baseUrl+'#/policy_snapshot';
});
};
---------------------------------------------------------------------------------------------
Set baseurl or common url :
app.js
app.constant('MY_CONFIG', {
apiBaseUrl : 'http://localhost/api/',
baseUrl : 'http://localhost/projectName/',
});
---------------------------------------------------------------------------------------------
Local Storage Service :
localService.js
app.factory("LocalService", ['$http', '$rootScope','MY_CONFIG','$cookies',
function ($http, $rootScope,MY_CONFIG,$cookies) {
var serviceBase = MY_CONFIG.apiBaseUrl;
var obj = {};
var config = {
cache: false,
headers: {
'clientToken': $cookies.get('clientToken')
}
};
obj.get = function (q) {
$rootScope.showLoader = true;
return $http.get(q, config).then(function (results) {
$rootScope.showLoader = false;
return results;
},function (error) {
$rootScope.showLoader = false;
});
};
obj.post = function (q, object) {
$rootScope.showLoader = true;
return $http.post(q, object, config).then(function (results) {
$rootScope.showLoader = false;
return results.data;
}, function (error) {
$rootScope.showLoader = false;
});
};
return obj;
}]);
---------------------------------------------------------------------------------------------
set/get/remove cookies Values :
Set :
$cookies.put('clientToken', cookies.value);
Get:
$cookies.get('clientToken');
Remove :
$cookies.remove('clientToken');
use cookies js : https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular-cookies.min.js
---------------------------------------------------------------------------------------------
Pass object from one controller to onother controller :
homeController.js
In success :
$rootScope.userList = response.data;
var token = JSON.stringify($rootScope.userList); // object convert to string
$window.localStorage.setItem("userList",token); // set item value
$window.location = MY_CONFIG.baseUrl+'#/another_page';
otherController.js
var userList = angular.fromJson($window.localStorage.getItem("userList")); //string convert to object and get value
$scope.userSearchList = userList;
---------------------------------------------------------------------------------------------
Ternary condition in model (if condition):
{{$index === 0 ? 'ifCondition' : 'elseCondition'}}
---------------------------------------------------------------------------------------------
Filter amount in INR:
app.js
app.filter('INR', function () {
return function (input) {
if (! isNaN(input)) {
var currencySymbol = '₹ ';
//var output = Number(input).toLocaleString('en-IN'); <-- This method is not working fine in all browsers!
var result = input.toString().split('.');
var lastThree = result[0].substring(result[0].length - 3);
var otherNumbers = result[0].substring(0, result[0].length - 3);
if (otherNumbers != '')
lastThree = ',' + lastThree;
var output = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;
if (result.length > 1) {
output += "." + result[1];
}
return currencySymbol + output;
}
}
});
{{9892784 | INR}} // e.g. 9892784 in amout
Output : ₹ 98,92,784
---------------------------------------------------------------------------------------------
Navigation active tab based on url :
View :
<ul class="nav navbar-nav" bs-navbar>
<li data-match-route="/home">
<a href="#/home">Home</a>
</li>
<li data-match-route="/about">
<a href="#/about">About Us</a>
</li>
</ul>
app.js
app.directive('bsNavbar', ['$location', function ($location) {
return {
restrict: 'A',
link: function postLink(scope, element,$scope) {
scope.$watch(function () {
return $location.path();
}, function (path) {
angular.forEach(element.children(), (function (li) {
var $li = angular.element(li),
regex = new RegExp('^' + $li.attr('data-match-route') + '$', 'i'),
isActive = regex.test(path);
$li.toggleClass('active', isActive); //active is class name
}));
});
}
};
}]);
---------------------------------------------------------------------------------------------
ng-include show-hide using directive (index.html) :
View :
<div hideon="show" ng-include="'components/shared/header/headerView.html'"></div>
app.js
app.directive('hideon',['$location', function($location) {
return {
restrict: 'A',
link: function postLink(scope, element, attrs) {
scope.$watch(function () {
return $location.path();
}, function (path) {
var favoriteCookie = $location.path();
if(favoriteCookie == '/login') { //if /login url then page hide otherwise page show
element.hide();
} else {
element.show();
}
}, true);
}
};
}]);
---------------------------------------------------------------------------------------------
Responding to idle user in angular js applications :
app.js
app.config(['IdleProvider',function(IdleProvider){
IdleProvider.idle(10*60); //1 min = 60
IdleProvider.timeout(1*5);
KeepaliveProvider.interval(10);
}
app.run(['$rootScope','Idle','$cookies','$window','MY_CONFIG',function($rootScope, Idle,$cookies,$window,MY_CONFIG) {
Idle.watch();
$rootScope.$on('IdleStart', function() {
// console.log("I am inside Idle Start function");
/* Display modal warning or sth */
});
$rootScope.$on('IdleTimeout', function() {
$cookies.remove("clientToken");
$window.location.reload();
$window.location = MY_CONFIG.baseUrl+'#/login';
});
}]);
---------------------------------------------------------------------------------------------
Export data in Excel, Pdf, CVS and Doc :
View Part
<script src="tableExport.js"></script>
<script src="app/jquery.base64.js"></script>
<script src="app/sprintf.js"></script>
<script src="app/jspdf.js"></script>
<script src="app/base64.js"></script>
<table class="export-table" style="width: 100%; margin-top: 20px">
<thead>
<tr>
<th>Employee ID</th>
<th>Last Name</th>
<th>First Name</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in reportData">
<td>{{item.EmployeeID}}</td>
<td>{{item.LastName}}</td>
<td>{{item.FirstName}}</td>
<td>{{item.Salary}}</td>
</tr>
</tbody>
</table>
<a href="#" data-ng-click="exportAction('csv')"> Export CSV</a><br/><br/>
<a href="#" data-ng-click="exportAction('excel')"> Export Excel</a><br/><br/>
<a href="#" data-ng-click="exportAction('doc')"> Export Doc</a><br/><br/>
<a href="#" data-ng-click="exportAction('pdf')"> Export Pdf</a><br/><br/>
Controller Part
$scope.exportAction = function (option) {
switch (option) {
case 'pdf': $scope.$broadcast('export-pdf', {});
break;
case 'excel': $scope.$broadcast('export-excel', {});
break;
case 'doc': $scope.$broadcast('export-doc', {});
break;
case 'csv': $scope.$broadcast('export-csv', {});
break;
default: console.log('no event caught');
}
}
app.directive('exportTable', function(){
var link = function ($scope, elm, attr) {
$scope.$on('export-pdf', function (e, d) {
elm.tableExport({ type: 'pdf', escape: false });
});
$scope.$on('export-excel', function (e, d) {
elm.tableExport({ type: 'excel', escape: false });
});
$scope.$on('export-doc', function (e, d) {
elm.tableExport({ type: 'doc', escape: false });
});
$scope.$on('export-csv', function (e, d) {
elm.tableExport({ type: 'csv', escape: false });
});
}
return {
restrict: 'C',
link: link
}
});
---------------------------------------------------------------------------------------------
Export data in Excel(.xls) and CVS without table format :
app.js
var app = angular.module('myPortal', ['ngRoute', 'ui.bootstrap', '720kb.datepicker', 'ngIdle', 'ngCookies', 'ngJsonExportExcel']);
View Part
<!--1) In json-export-excel.js file directive is ngJsonExportExcel-->
<!--2) In json-export-excel.js file Change Extension csv in line number 34 then csv file download-->
<script src="json-export-excel.js"></script>
<script src="fileSaver.js"></script>
<button ng-json-export-excel data="dataList" report-fields="columnList" filename =" 'Customer Portfolio' " class="css-class">
Download
</button>
Controller :
$scope.columnList = { SrNo : 'sr. No.', userName: 'User Name', dob: 'Date Of Birth', emailId: 'Email Id', MobileNo: 'mobileNo' };
$scope.dataList = [{ SrNo : '1', userName: 'ABC', dob: '07-12-1988', emailId: 'abc@gmail.com', MobileNo: '9221460041' },
{ SrNo : '2', userName: 'DCF', dob: '07-12-1988', emailId: 'dcf@gmail.com', MobileNo: '9221460041' }];
---------------------------------------------------------------------------------------------
Download any file on click :
View :
<a ng-click="download()" href="javascript:void(0);">
<img src="assets/images/pdf-icon.png" alt=""/>
</a>
Controller :
$scope.download = function() {
var linkPDF = $scope.fileURL; // link name (http://localhost/content/PDF/fileName.pdf)
var fileNamedown = 'fileName.pdf';
var linkElement = document.createElement('a');
linkElement.setAttribute('href', linkPDF);
linkElement.setAttribute("download", fileNamedown);
var clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
linkElement.dispatchEvent(clickEvent);
}
Refer Link : http://jaliyaudagedara.blogspot.in/2016/05/angularjs-download-files-by-sending.html
---------------------------------------------------------------------------------------------
Input to only accept number :
View :
<input type="text" required maxlength="10" numeric-only class="input-field" ng-model="txtMobileNo" name="txtMobileNo" placeholder="Mobile Number*" />
Controller :
app.directive('numericOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'') : null;
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
---------------------------------------------------------------------------------------------
Input to only accept character :
View :
<input type="text" no-character ng-model="userName" name="userName" placeholder="User Name*" />
Controller :
app.directive('ngCharacter', function() {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModelCtrl) {
function fromUser(text) {
var transformedInput = text.replace(/[^A-Za-z ]/g, '');
if(transformedInput !== text) {
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
}
return transformedInput;
}
ngModelCtrl.$parsers.push(fromUser);
}
};
});
---------------------------------------------------------------------------------------------
Input to special character not allowed :
View :
<input type="text" no-special-char ng-model="userName" name="userName" placeholder="User Name*" />
Controller :
app.directive('noSpecialChar', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(inputValue) {
if (inputValue == null)
return ''
var cleanInputValue = inputValue.replace(/[^\w\s]/gi, '');
if (cleanInputValue != inputValue) {
modelCtrl.$setViewValue(cleanInputValue);
modelCtrl.$render();
}
return cleanInputValue;
});
}
};
});
---------------------------------------------------------------------------------------------
Normal Form Validation :
View : //((txtPolicyNo || txtMobileNo) && txtDOB)
<form name="userForm" ng-submit="customerSearch()">
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-6 marginb15">
<input type="text" ng-required='!txtPolicyNo' maxlength="10" numeric-only class="input-field" ng-model="txtMobileNo" name="txtMobileNo" placeholder="Mobile Number*" />
</div>
<div class="col-md-6 col-sm-6 col-xs-6 marginb15 relative">
<input type="text" ng-required='!txtMobileNo' class="input-field" ng-model="txtPolicyNo" name="txtPolicyNo" placeholder="Policy Number*" />
<span class="addor">OR</span>
</div>
<p ng-show='userForm.txtPolicyNo.$error.required && userForm.txtPolicyNo.$dirty || userForm.txtMobileNo.$error.required && userForm.txtMobileNo.$dirty'>
Mobile Number OR Policy Number Required
</p>
<div class="col-md-6 col-sm-6 col-xs-6 marginb15">
<input type="text" required class="input-field" ng-model="txtDOB" name="txtDOB" placeholder="Date of Birth* (17/June/1988)" />
<span ng-show="userForm.txtDOB.$invalid && userForm.txtDOB.$dirty">
Please Select DOB
</span>
</div>
<div class="col-md-6 col-sm-6 col-xs-6 marginb15 searchbx">
<button type="submit" class="commonbtn" ng-disabled="userForm.$invalid" >Submit</button>
</div>
</div>
</form>
---------------------------------------------------------------------------------------------
Inline Form Validation :
View : //((txtPolicyNo || txtMobileNo) && txtDOB)
<form name="userForm" ng-submit="customerSearch()">
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-6 marginb15">
<input type="text" ng-required='!txtPolicyNo' maxlength="10" numeric-only class="input-field" ng-model="txtMobileNo" name="txtMobileNo" placeholder="Mobile Number*" />
</div>
<div class="col-md-6 col-sm-6 col-xs-6 marginb15 relative">
<input type="text" ng-required='!txtMobileNo' class="input-field" ng-model="txtPolicyNo" name="txtPolicyNo" placeholder="Policy Number*" />
<span class="addor">OR</span>
</div>
<div class="col-md-12 col-sm-12 col-xs-12 marginb15">
<p class="errortxt" ng-show="submitted && userForm.txtPolicyNo.$error.required" >
Mobile Number OR Policy Number Required.
</p>
</div>
<div class="col-md-6 col-sm-6 col-xs-6 marginb15">
<datepicker date-format="dd/MM/yyyy" selector="datepick" button-prev="<i class='fa fa-arrow-left'></i>" button-next="<i class='fa fa-arrow-right'></i>">
<div class="input-group datepickbox">
<input type="text" readonly="" required class="datepick input-field" ng-model="txtDOB" name="txtDOB" placeholder="Date of Birth* "/>
<span class="input-group-addon" style="cursor: pointer">
<i class="fa fa-lg fa-calendar"></i>
</span>
</div>
</datepicker>
<span class="fullwidth errortxt paddingt15" ng-show="submitted && userForm.txtDOB.$error.required">
Please Select DOB.
</span>
</div>
<div class="col-md-6 col-sm-6 col-xs-6 marginb15 searchbx">
<button type="submit" class="commonbtn" ng-click="submitted=true" >Submit</button>
</div>
</div>
</form>
---------------------------------------------------------------------------------------------
Search based on parameters with object filter count :
View :
<!--Search Only Customer Name-->
<input type="text" placeholder="Enter Name" ng-model="searchFilter.customerName" />
<!--customerPortfolioList is object name-->
<div ng-repeat="customerPortfolio in filteredItems = ( customerPortfolioList | filter : searchFilter)">
<h1>{{customerPortfolio.customerName}}</h1>
</div>
<div ng-if='filteredItems.length === 0'>
<div>Sorry , No Data Found</div>
</div>
---------------------------------------------------------------------------------------------
Datepicker :
<link href="assets/css/angular-datepicker.css" rel="stylesheet" type="text/css"/>
<script src="assets/js/angular-datepicker.js" type="text/javascript"></script>
app.js
var app = angular.module('myPortal', ['ngRoute', 'ui.bootstrap', '720kb.datepicker','ngIdle','ngCookies','ngJsonExportExcel']);
View :
<datepicker date-format="dd/MM/yyyy" selector="datepick" button-prev="<i class='fa fa-arrow-left'></i>" button-next="<i class='fa fa-arrow-right'></i>">
<div class="input-group datepickbox">
<input type="text" readonly="" required class="datepick input-field" ng-model="txtDOB" name="txtDOB" placeholder="Date of Birth* "/>
<span class="input-group-addon" style="cursor: pointer">
<i class="fa fa-lg fa-calendar"></i>
</span>
</div>
</datepicker>
Refer Link : https://github.com/720kb/ angular-datepicker
---------------------------------------------------------------------------------------------
ng-repeat $index to pass data form view to controller :
View :
<div ng-repeat="user in userList">
<a ng-click="sendInfo($index)" href="javascript:void(0);">
User Info
</a>
</div>
Controller :
$scope.sendSms = function(index){
console.log($scope.userList[index]);
};
---------------------------------------------------------------------------------------------
Object multiple key to filter data and get filter object count and filter data pass form view to controller :
View :
<input type="text" ng-keyup="SendData(filterUserList)" id="searchText" placeholder="Enter User Name Or Mobile Number Or Email ID" ng-model="searchText" />
<div ng-repeat="userInfo in filterUserList = ( userMasterList | filter:{searchData:searchText})" ng-init="userInfo.searchData = buildSearchData(userInfo)">
<div>{{userInfo.userName}}</div>
<div>{{userInfo.gender}}</div>
<div>{{userInfo.mobileNo}}</div>
<div>{{userInfo.address}}</div>
<div>{{userInfo.emailId}}</div>
</div>
<div ng-if='filterUserList.length === 0'>
Sorry , No Data Found
</div>
Controller :
//filter for multiple object key
$scope.buildSearchData = buildSearchData;
function buildSearchData(friend){
return friend.userName + ' ' + friend.mobileNo + ' ' + friend.emailId;
}
$scope.SendData = function(data){
$scope.dataList = data;
};
---------------------------------------------------------------------------------------------
Directory Structure :
refer link : https://scotch.io/tutorials/angularjs-best-practices-directory-structure
---------------------------------------------------------------------------------------------
Set module and route :
app.js
var app = angular.module('myModule', ['ngRoute', 'ui.bootstrap', '720kb.datepicker','ngIdle','ngCookies']);
app.config(['$routeProvider','KeepaliveProvider', 'IdleProvider','$locationProvider',function($routeProvider,KeepaliveProvider,IdleProvider,$locationProvider){
$routeProvider
.otherwise('/home',{
templateUrl:'components/home/homeView.html',
controller:'homeController'
})
.when('/home',{
templateUrl:'components/home/homeView.html',
controller:'homeController'
})
.when('/login',{
templateUrl:'components/login/loginView.html',
controller:'loginController'
});
}]);
use js :
https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular.min.js
https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular-route.min.js
---------------------------------------------------------------------------------------------
homeController.js :
app.controller("homeController",,['$rootScope','$scope','LocalService','$cookies','$window','MY_CONFIG','$location','$route','$http',function($rootScope,$scope,LocalService,$cookies,$window,MY_CONFIG,$location,$route,$http){
//check cookie values - if value is empty then redirect to login url
var favoriteCookie = $cookies.get('clientToken');
if(favoriteCookie == undefined){
$window.location = MY_CONFIG.baseUrl+'#/login';
}
$scope.collectionAPI = false; //function load only one
$scope.callFunctionByHttp = function(){
if(!$scope.collectionAPI){
$scope.loading = true;
$http({
method: 'POST',
headers: {
clientToken: favoriteCookie
},
url: MY_CONFIG.apiBaseUrl + 'loadDataFunctionName'
}).then(function successCallback(response) {
$scope.collectionData = response.data.data;
$scope.collectionList = response.data.data.collectionListDate;
$scope.collectionAPI = !$scope.collectionAPI;
$scope.loading = false;
}, function errorCallback(response) {
});
};
$scope.newAPI = false;
$scope.callFunctionTo = function(){
if(!$scope.newAPI){
$scope.loading = true;
LocalService.post(MY_CONFIG.apiBaseUrl + 'loadDataFunctionName').then(function(response){
$scope.newData = response.data;
$scope.newList = response.data.newDataListDate;
$scope.newAPI = !$scope.newAPI;
$scope.loading = false;
});
}
};
}]);
---------------------------------------------------------------------------------------------
loginController.js :
app.controller("loginController",['$scope','LocalService','$cookies','$window','MY_CONFIG','$http','$location', function($scope,LocalService,$cookies,$window,MY_CONFIG,$http,$location){
$scope.title ='Login View';
$scope.username = 'admin';
$scope.password = 'admin@123';
$scope.userLogin = function(){
$http({
method: 'POST',
url: MY_CONFIG.apiBaseUrl+'Login',
headers: {
'Authorization' : 'Basic ' + Base64.encode($scope.username+':'+$scope.password)
}
}).then(function(response){
$cookies.put('clientToken', response.data.data.clientToken);
$window.location = MY_CONFIG.baseUrl+'#/home';
});
};
}]);
---------------------------------------------------------------------------------------------
Post form data to controller :
View :
<form name="userForm" ng-submit="customerSearch()">
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-6 marginb15">
<input type="text" ng-required='!txtPolicyNo' maxlength="10" numeric-only class="input-field" ng-model="txtMobileNo" name="txtMobileNo" placeholder="Mobile Number*" />
</div>
<div class="col-md-6 col-sm-6 col-xs-6 marginb15 relative">
<input type="text" ng-required='!txtMobileNo' class="input-field" ng-model="txtPolicyNo" name="txtPolicyNo" placeholder="Policy Number*" />
<span class="addor">OR</span>
</div>
<p ng-show='userForm.txtPolicyNo.$error.required && userForm.txtPolicyNo.$dirty || userForm.txtMobileNo.$error.required && userForm.txtMobileNo.$dirty'>
Mobile Number OR Policy Number Required
</p>
<div class="col-md-6 col-sm-6 col-xs-6 marginb15">
<input type="text" required class="input-field" ng-model="txtDOB" name="txtDOB" placeholder="Date of Birth* (17/June/1988)" />
<span ng-show="userForm.txtDOB.$invalid && userForm.txtDOB.$dirty">
Please Select DOB
</span>
</div>
<div class="col-md-6 col-sm-6 col-xs-6 marginb15 searchbx">
<button type="submit" class="commonbtn" ng-disabled="userForm.$invalid" >Submit</button>
</div>
</div>
</form>
app.js
$scope.customerSearch = function(){
$scope.quickCustomerSearch = {
'mobileNo':$scope.txtMobileNo,
'policyNo':$scope.txtPolicyNo,
'DOB':$scope.txtDOB
};
$http({
method : 'POST',
url : MY_CONFIG.apiBaseUrl + "saveData",
data : $scope.quickCustomerSearch, //forms user object
headers : {'Content-Type':'application/json; charset=utf-8','clientToken': favoriteCookie}
})
.success(function(response) {
$rootScope.policySummary = response.data;
var policySummary = JSON.stringify($rootScope.policySummary);
$window.localStorage.setItem("policySummary",policySummary);
$window.location = MY_CONFIG.baseUrl+'#/policy_snapshot';
});
};
---------------------------------------------------------------------------------------------
Set baseurl or common url :
app.js
app.constant('MY_CONFIG', {
apiBaseUrl : 'http://localhost/api/',
baseUrl : 'http://localhost/projectName/',
});
---------------------------------------------------------------------------------------------
Local Storage Service :
localService.js
app.factory("LocalService", ['$http', '$rootScope','MY_CONFIG','$cookies',
function ($http, $rootScope,MY_CONFIG,$cookies) {
var serviceBase = MY_CONFIG.apiBaseUrl;
var obj = {};
var config = {
cache: false,
headers: {
'clientToken': $cookies.get('clientToken')
}
};
obj.get = function (q) {
$rootScope.showLoader = true;
return $http.get(q, config).then(function (results) {
$rootScope.showLoader = false;
return results;
},function (error) {
$rootScope.showLoader = false;
});
};
obj.post = function (q, object) {
$rootScope.showLoader = true;
return $http.post(q, object, config).then(function (results) {
$rootScope.showLoader = false;
return results.data;
}, function (error) {
$rootScope.showLoader = false;
});
};
return obj;
}]);
---------------------------------------------------------------------------------------------
set/get/remove cookies Values :
Set :
$cookies.put('clientToken', cookies.value);
Get:
$cookies.get('clientToken');
Remove :
$cookies.remove('clientToken');
use cookies js : https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular-cookies.min.js
---------------------------------------------------------------------------------------------
Pass object from one controller to onother controller :
homeController.js
In success :
$rootScope.userList = response.data;
var token = JSON.stringify($rootScope.userList); // object convert to string
$window.localStorage.setItem("userList",token); // set item value
$window.location = MY_CONFIG.baseUrl+'#/another_page';
otherController.js
var userList = angular.fromJson($window.localStorage.getItem("userList")); //string convert to object and get value
$scope.userSearchList = userList;
---------------------------------------------------------------------------------------------
Ternary condition in model (if condition):
{{$index === 0 ? 'ifCondition' : 'elseCondition'}}
---------------------------------------------------------------------------------------------
Filter amount in INR:
app.js
app.filter('INR', function () {
return function (input) {
if (! isNaN(input)) {
var currencySymbol = '₹ ';
//var output = Number(input).toLocaleString('en-IN'); <-- This method is not working fine in all browsers!
var result = input.toString().split('.');
var lastThree = result[0].substring(result[0].length - 3);
var otherNumbers = result[0].substring(0, result[0].length - 3);
if (otherNumbers != '')
lastThree = ',' + lastThree;
var output = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;
if (result.length > 1) {
output += "." + result[1];
}
return currencySymbol + output;
}
}
});
{{9892784 | INR}} // e.g. 9892784 in amout
Output : ₹ 98,92,784
---------------------------------------------------------------------------------------------
Navigation active tab based on url :
View :
<ul class="nav navbar-nav" bs-navbar>
<li data-match-route="/home">
<a href="#/home">Home</a>
</li>
<li data-match-route="/about">
<a href="#/about">About Us</a>
</li>
</ul>
app.js
app.directive('bsNavbar', ['$location', function ($location) {
return {
restrict: 'A',
link: function postLink(scope, element,$scope) {
scope.$watch(function () {
return $location.path();
}, function (path) {
angular.forEach(element.children(), (function (li) {
var $li = angular.element(li),
regex = new RegExp('^' + $li.attr('data-match-route') + '$', 'i'),
isActive = regex.test(path);
$li.toggleClass('active', isActive); //active is class name
}));
});
}
};
}]);
---------------------------------------------------------------------------------------------
ng-include show-hide using directive (index.html) :
View :
<div hideon="show" ng-include="'components/shared/header/headerView.html'"></div>
app.js
app.directive('hideon',['$location', function($location) {
return {
restrict: 'A',
link: function postLink(scope, element, attrs) {
scope.$watch(function () {
return $location.path();
}, function (path) {
var favoriteCookie = $location.path();
if(favoriteCookie == '/login') { //if /login url then page hide otherwise page show
element.hide();
} else {
element.show();
}
}, true);
}
};
}]);
---------------------------------------------------------------------------------------------
Responding to idle user in angular js applications :
app.js
app.config(['IdleProvider',function(IdleProvider){
IdleProvider.idle(10*60); //1 min = 60
IdleProvider.timeout(1*5);
KeepaliveProvider.interval(10);
}
app.run(['$rootScope','Idle','$cookies','$window','MY_CONFIG',function($rootScope, Idle,$cookies,$window,MY_CONFIG) {
Idle.watch();
$rootScope.$on('IdleStart', function() {
// console.log("I am inside Idle Start function");
/* Display modal warning or sth */
});
$rootScope.$on('IdleTimeout', function() {
$cookies.remove("clientToken");
$window.location.reload();
$window.location = MY_CONFIG.baseUrl+'#/login';
});
}]);
---------------------------------------------------------------------------------------------
Export data in Excel, Pdf, CVS and Doc :
View Part
<script src="tableExport.js"></script>
<script src="app/jquery.base64.js"></script>
<script src="app/sprintf.js"></script>
<script src="app/jspdf.js"></script>
<script src="app/base64.js"></script>
<table class="export-table" style="width: 100%; margin-top: 20px">
<thead>
<tr>
<th>Employee ID</th>
<th>Last Name</th>
<th>First Name</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in reportData">
<td>{{item.EmployeeID}}</td>
<td>{{item.LastName}}</td>
<td>{{item.FirstName}}</td>
<td>{{item.Salary}}</td>
</tr>
</tbody>
</table>
<a href="#" data-ng-click="exportAction('csv')"> Export CSV</a><br/><br/>
<a href="#" data-ng-click="exportAction('excel')"> Export Excel</a><br/><br/>
<a href="#" data-ng-click="exportAction('doc')"> Export Doc</a><br/><br/>
<a href="#" data-ng-click="exportAction('pdf')"> Export Pdf</a><br/><br/>
Controller Part
$scope.exportAction = function (option) {
switch (option) {
case 'pdf': $scope.$broadcast('export-pdf', {});
break;
case 'excel': $scope.$broadcast('export-excel', {});
break;
case 'doc': $scope.$broadcast('export-doc', {});
break;
case 'csv': $scope.$broadcast('export-csv', {});
break;
default: console.log('no event caught');
}
}
app.directive('exportTable', function(){
var link = function ($scope, elm, attr) {
$scope.$on('export-pdf', function (e, d) {
elm.tableExport({ type: 'pdf', escape: false });
});
$scope.$on('export-excel', function (e, d) {
elm.tableExport({ type: 'excel', escape: false });
});
$scope.$on('export-doc', function (e, d) {
elm.tableExport({ type: 'doc', escape: false });
});
$scope.$on('export-csv', function (e, d) {
elm.tableExport({ type: 'csv', escape: false });
});
}
return {
restrict: 'C',
link: link
}
});
---------------------------------------------------------------------------------------------
Export data in Excel(.xls) and CVS without table format :
app.js
var app = angular.module('myPortal', ['ngRoute', 'ui.bootstrap', '720kb.datepicker', 'ngIdle', 'ngCookies', 'ngJsonExportExcel']);
View Part
<!--1) In json-export-excel.js file directive is ngJsonExportExcel-->
<!--2) In json-export-excel.js file Change Extension csv in line number 34 then csv file download-->
<script src="json-export-excel.js"></script>
<script src="fileSaver.js"></script>
<button ng-json-export-excel data="dataList" report-fields="columnList" filename =" 'Customer Portfolio' " class="css-class">
Download
</button>
Controller :
$scope.columnList = { SrNo : 'sr. No.', userName: 'User Name', dob: 'Date Of Birth', emailId: 'Email Id', MobileNo: 'mobileNo' };
$scope.dataList = [{ SrNo : '1', userName: 'ABC', dob: '07-12-1988', emailId: 'abc@gmail.com', MobileNo: '9221460041' },
{ SrNo : '2', userName: 'DCF', dob: '07-12-1988', emailId: 'dcf@gmail.com', MobileNo: '9221460041' }];
---------------------------------------------------------------------------------------------
Download any file on click :
View :
<a ng-click="download()" href="javascript:void(0);">
<img src="assets/images/pdf-icon.png" alt=""/>
</a>
Controller :
$scope.download = function() {
var linkPDF = $scope.fileURL; // link name (http://localhost/content/PDF/fileName.pdf)
var fileNamedown = 'fileName.pdf';
var linkElement = document.createElement('a');
linkElement.setAttribute('href', linkPDF);
linkElement.setAttribute("download", fileNamedown);
var clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
linkElement.dispatchEvent(clickEvent);
}
Refer Link : http://jaliyaudagedara.blogspot.in/2016/05/angularjs-download-files-by-sending.html
---------------------------------------------------------------------------------------------
Input to only accept number :
View :
<input type="text" required maxlength="10" numeric-only class="input-field" ng-model="txtMobileNo" name="txtMobileNo" placeholder="Mobile Number*" />
Controller :
app.directive('numericOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'') : null;
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
---------------------------------------------------------------------------------------------
Input to only accept character :
View :
<input type="text" no-character ng-model="userName" name="userName" placeholder="User Name*" />
Controller :
app.directive('ngCharacter', function() {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModelCtrl) {
function fromUser(text) {
var transformedInput = text.replace(/[^A-Za-z ]/g, '');
if(transformedInput !== text) {
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
}
return transformedInput;
}
ngModelCtrl.$parsers.push(fromUser);
}
};
});
---------------------------------------------------------------------------------------------
Input to special character not allowed :
View :
<input type="text" no-special-char ng-model="userName" name="userName" placeholder="User Name*" />
Controller :
app.directive('noSpecialChar', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(inputValue) {
if (inputValue == null)
return ''
var cleanInputValue = inputValue.replace(/[^\w\s]/gi, '');
if (cleanInputValue != inputValue) {
modelCtrl.$setViewValue(cleanInputValue);
modelCtrl.$render();
}
return cleanInputValue;
});
}
};
});
---------------------------------------------------------------------------------------------
Normal Form Validation :
View : //((txtPolicyNo || txtMobileNo) && txtDOB)
<form name="userForm" ng-submit="customerSearch()">
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-6 marginb15">
<input type="text" ng-required='!txtPolicyNo' maxlength="10" numeric-only class="input-field" ng-model="txtMobileNo" name="txtMobileNo" placeholder="Mobile Number*" />
</div>
<div class="col-md-6 col-sm-6 col-xs-6 marginb15 relative">
<input type="text" ng-required='!txtMobileNo' class="input-field" ng-model="txtPolicyNo" name="txtPolicyNo" placeholder="Policy Number*" />
<span class="addor">OR</span>
</div>
<p ng-show='userForm.txtPolicyNo.$error.required && userForm.txtPolicyNo.$dirty || userForm.txtMobileNo.$error.required && userForm.txtMobileNo.$dirty'>
Mobile Number OR Policy Number Required
</p>
<div class="col-md-6 col-sm-6 col-xs-6 marginb15">
<input type="text" required class="input-field" ng-model="txtDOB" name="txtDOB" placeholder="Date of Birth* (17/June/1988)" />
<span ng-show="userForm.txtDOB.$invalid && userForm.txtDOB.$dirty">
Please Select DOB
</span>
</div>
<div class="col-md-6 col-sm-6 col-xs-6 marginb15 searchbx">
<button type="submit" class="commonbtn" ng-disabled="userForm.$invalid" >Submit</button>
</div>
</div>
</form>
---------------------------------------------------------------------------------------------
Inline Form Validation :
View : //((txtPolicyNo || txtMobileNo) && txtDOB)
<form name="userForm" ng-submit="customerSearch()">
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-6 marginb15">
<input type="text" ng-required='!txtPolicyNo' maxlength="10" numeric-only class="input-field" ng-model="txtMobileNo" name="txtMobileNo" placeholder="Mobile Number*" />
</div>
<div class="col-md-6 col-sm-6 col-xs-6 marginb15 relative">
<input type="text" ng-required='!txtMobileNo' class="input-field" ng-model="txtPolicyNo" name="txtPolicyNo" placeholder="Policy Number*" />
<span class="addor">OR</span>
</div>
<div class="col-md-12 col-sm-12 col-xs-12 marginb15">
<p class="errortxt" ng-show="submitted && userForm.txtPolicyNo.$error.required" >
Mobile Number OR Policy Number Required.
</p>
</div>
<div class="col-md-6 col-sm-6 col-xs-6 marginb15">
<datepicker date-format="dd/MM/yyyy" selector="datepick" button-prev="<i class='fa fa-arrow-left'></i>" button-next="<i class='fa fa-arrow-right'></i>">
<div class="input-group datepickbox">
<input type="text" readonly="" required class="datepick input-field" ng-model="txtDOB" name="txtDOB" placeholder="Date of Birth* "/>
<span class="input-group-addon" style="cursor: pointer">
<i class="fa fa-lg fa-calendar"></i>
</span>
</div>
</datepicker>
<span class="fullwidth errortxt paddingt15" ng-show="submitted && userForm.txtDOB.$error.required">
Please Select DOB.
</span>
</div>
<div class="col-md-6 col-sm-6 col-xs-6 marginb15 searchbx">
<button type="submit" class="commonbtn" ng-click="submitted=true" >Submit</button>
</div>
</div>
</form>
---------------------------------------------------------------------------------------------
Search based on parameters with object filter count :
View :
<!--Search Only Customer Name-->
<input type="text" placeholder="Enter Name" ng-model="searchFilter.customerName" />
<!--customerPortfolioList is object name-->
<div ng-repeat="customerPortfolio in filteredItems = ( customerPortfolioList | filter : searchFilter)">
<h1>{{customerPortfolio.customerName}}</h1>
</div>
<div ng-if='filteredItems.length === 0'>
<div>Sorry , No Data Found</div>
</div>
---------------------------------------------------------------------------------------------
Datepicker :
<link href="assets/css/angular-datepicker.css" rel="stylesheet" type="text/css"/>
<script src="assets/js/angular-datepicker.js" type="text/javascript"></script>
app.js
var app = angular.module('myPortal', ['ngRoute', 'ui.bootstrap', '720kb.datepicker','ngIdle','ngCookies','ngJsonExportExcel']);
View :
<datepicker date-format="dd/MM/yyyy" selector="datepick" button-prev="<i class='fa fa-arrow-left'></i>" button-next="<i class='fa fa-arrow-right'></i>">
<div class="input-group datepickbox">
<input type="text" readonly="" required class="datepick input-field" ng-model="txtDOB" name="txtDOB" placeholder="Date of Birth* "/>
<span class="input-group-addon" style="cursor: pointer">
<i class="fa fa-lg fa-calendar"></i>
</span>
</div>
</datepicker>
Refer Link : https://github.com/720kb/
---------------------------------------------------------------------------------------------
ng-repeat $index to pass data form view to controller :
View :
<div ng-repeat="user in userList">
<a ng-click="sendInfo($index)" href="javascript:void(0);">
User Info
</a>
</div>
Controller :
$scope.sendSms = function(index){
console.log($scope.userList[index]);
};
---------------------------------------------------------------------------------------------
Object multiple key to filter data and get filter object count and filter data pass form view to controller :
View :
<input type="text" ng-keyup="SendData(filterUserList)" id="searchText" placeholder="Enter User Name Or Mobile Number Or Email ID" ng-model="searchText" />
<div ng-repeat="userInfo in filterUserList = ( userMasterList | filter:{searchData:searchText})" ng-init="userInfo.searchData = buildSearchData(userInfo)">
<div>{{userInfo.userName}}</div>
<div>{{userInfo.gender}}</div>
<div>{{userInfo.mobileNo}}</div>
<div>{{userInfo.address}}</div>
<div>{{userInfo.emailId}}</div>
</div>
<div ng-if='filterUserList.length === 0'>
Sorry , No Data Found
</div>
Controller :
//filter for multiple object key
$scope.buildSearchData = buildSearchData;
function buildSearchData(friend){
return friend.userName + ' ' + friend.mobileNo + ' ' + friend.emailId;
}
$scope.SendData = function(data){
$scope.dataList = data;
};
---------------------------------------------------------------------------------------------
Great blog thanks for sharing Your website is the portal to your brand identity. The look and feel of every page carry a strong message. This is why your brand needs the best web design company in chennai to capture your visions and make it art. Adhuntt Media is graced with the most creative design team in Chennai.
ReplyDeletedigital marketing company in chennai
I have read your blog and i got a very useful and knowledgeable information from your blog.
ReplyDeleteAngular JS Online training
Angular JS training in Hyderabad
The way of you expressing your ideas is really good.you gave more useful ideas for us and please update more ideas for the learners.
ReplyDeleteAndroid Training Institute in Chennai | Android Training Institute in anna nagar | Android Training Institute in omr | Android Training Institute in porur | Android Training Institute in tambaram | Android Training Institute in velachery