Tuesday, 26 April 2016

Disable submit button until all mandatory fields are filled - Angular

Here I am going to explain how we can disable a submit button using a simple reusable directive until all the mandatory fields are filled. I have explained same using Angular 2 concept as well, please check this link for that. Let us start with a simple form first

Html


<div ng-app="sampleapp">
    <div ng-controller="samplecontoller" >
     <form name="form" disable-btn ng-submit="submitForm()">
       <div>
          <input type="text" ng-model="model.name" required></input>
      </div>
      <div>
        <input type="number" ng-model="model.number" required></input>
       </div>
      <div>
        <button class="btn btn-primary" type="submit">Submit</button>
      </div>
    </form>  
    </div>
</div>


In the above html "disable-btn" is the directive which we are going to create. I have marked both fields are mandatory using required attribute. Let us start with our directive.

Angular directive for disabling submit button



angular.module('sampleapp').directive('disableBtn',
function() {
 return {
  restrict : 'A',
  link : function(scope, element, attrs) {
   var $el = $(element);
   var submitBtn = $el.find('button[type="submit"]');
   var _name = attrs.name;
   scope.$watch(_name + '.$valid', function(val) {
    if (val) {
     submitBtn.removeAttr('disabled');
    } else {
     submitBtn.attr('disabled', 'disabled');
    }
   });
  }
 };
}
);


We are done with our directive, now you can see that submit button will be disabled until all the mandatory fields are filled. Check the below fiddle and see how it is working.

Using the same directive you can handle pattern validation as well. Also you can set max length/min length. For example see the below sample form.


<input type="number"placeholder="Last Name"  ng-model="model.age" required></input>

<input type="text" ng-model="model.city" ng-minlength="2" ng-maxlength="20" required>

<input type="text" ng-model="model.phoneNumber" pattern="^(?=.*?[1-9])[0-9()-]+$" 
maxlength="25" placeholder="Phone Number" />  

Related Posts

1. Angular js client side pagination like google.

2. Angular Loader using font awesome icons

3. Angular js add class to active element


Friday, 27 November 2015

Difference between ng-repeat-start and ng-repeat-end: Angular

ng-repeat and ng-repeat-start works similar and for ng-repeat-start required an ng-repeat-end. We can check in detail with examples.

ng-repeat



$scope.items = ['one','two','three'];

<span ng-repeat = "item in items">{{item}}</span>


output



 one
 two
 three


ng-repeat-start and ng-repeat-end



<span ng-repeat-start = "item in items">
    start {{item}}
</span>     

<span>{{item}}</span>

<span ng-repeat-end = "item in items">
    end {{item}}
</span>


Output



 start one
 one
 end one

 start two
 two
 end two

 start three
 three
 end three


Here you can see it is repeating all the html code as well. Instead of repeating only parent element we can repeat series of elements as well.

Related Posts

1. Angular select all/de select all checkbox.

2. How to check lowercase in indexOf of an Array

3. Covert string to camel case using javascript

4. How to remove duplicate from an array and get count of duplicated .


Apply track by index and filter for ng-repeat: Angular

Angular default ng-repeat doesn't allow duplicate, for avoiding this you can add track by $index.



<div ng-repeat="user in userList track by $index">
    <span>{{user.name}}</span>
</div>


For applying filter you may try below code



<div ng-repeat="user in userList track by $index | filter:search">
    <span>{{user.name}}</span>
</div>


But it is not correct, filter should be done before applying track by $index.



<div ng-repeat="user in userList | filter:search track by $index">
    <span>{{user.name}}</span>
</div>


Whenever you are applying filter along with track by $index follow above one .You can have multiple filters.

You can read more about track by $index in angular js document

Related Posts

1. Angular js client side pagination like google.

2. Angular Loader using font awesome icons

3. Angular js add class to active element


Tuesday, 17 November 2015

Angular directive for scroll top.

If user is at the bottom of the page give an option to navigate to top of the page by clicking an arrow or button. We can create a simple directive to achieve this. I have written same using Angular 2 concept as well, click here to know more.

Add below directive at footer or where you want to display the arrow.


 <scroll-up></scroll-up>

Directive


angular.module("your-module-name").directive("scrollUp",
function(){
return{
 restrict: 'E',
 transclude: true,
 replace: true,
 template: '<a class="scrollTopBtn" ng-click="scrollToTop()">
             <img src ='image/arrow' alt="image" ></i>
           </a>',
 controller : function($scope){
  $scope.scrollToTop = function(){
    $('html, body').animate({scrollTop : 0},900);
  }
 },
 link : function( scope, element, attrs ){
  $(window).scroll(function(){
    if ($(this).scrollTop() > 200){
     $(".scrollTopBtn").css('display':'block');
    }else{
     $('.scrollTopBtn').css('display':'none');
    }
  });
  }
  }
 }
);

Related Posts

1. Angular js client side pagination like google.

2. Angular Loader using font awesome icons

3. Angular js add class to active element


Monday, 16 November 2015

Jquery select all/de select all checkbox

Let us check how we can make select/deselect check box using Jquery. I have explained the same using Angular js 1 and 2 as well. If you want to compare the implementation please check below post as well.

1. Select all/ deselect all check box using Angular js 1
2. Select all/ deselect all checkbox - Angular 2

Create a dynamic checkbox


//Html
<div class="wrapper"></div>
 
//JS
var _html = '<div class="list">
    <label><input type="checkbox" checked class="selectAll"> 
  Countries
    </label>';

var _list = ['USA','India','China','England','Japan'];

for ( var i = 0; i < _list.length; i++ )
{
_html += '<div class="checkbox">
 <label>
 <input type="checkbox" checked class="checkbox" value="' + _list[i] + '"/>' + _list[i] + '
 </label>
 </div>';
}

_html += '</div>'

$('.wrapper').after(_html);
 

Select All/De Select All features



$('.selectAll').change(function(){
  $(".checkbox").find(':checkbox').prop("checked", this.checked);  
});


Now you can see that select all/de select all feature is working fine .But if we unselect one of the checkbox then the master check box also need to uncheck and also if we select all check box master should also checked .For making this possible add below code as well.


$(".checkbox").change(function(){
 
 var _totalChecked = $('.checkbox').find('input:checked').length;
 
 if(_totalChecked == _list.length){
  
  $(".selectAll").prop("checked", true);
 
 }else{
  
  $(".selectAll").prop("checked", false);
 
 }

});

Related Posts

1. Angular select all/de select all checkbox.

2. How to check lowercase in indexOf of an Array

3. Covert string to camel case using javascript

4. How to remove duplicate from an array and get count of duplicated .


Check Array.indexOf() with case insensitive.

If it is not an array we can check easily like below example.


var _name = "prasho";

var _list = [{name:'prasho'},{name:'Gorge'}];

for(var i=0;i<_list.length;i++)
{
  if(_name.toLoweCase().indexOf(_list[i].name.toLoweCase()) != -1){
  //do what ever
  }else{
  //do what ever
  }
}

But if _name is an array then how we can make it lower case and check the indexOf


var _name = ['prasho','abraham','sam','anna']
var _list = [{name:'prasho'},{name:'Gorge'}];

for(var i=0;i<_list.length;i++)
{
   if(_name.map(function (c) {
     return c.toLowerCase();
   }).indexOf(_list[i].name.toLowerCase()) != -1) { 
  //do what ever
   }else{
     //do what ever
   }
}

Related Posts

1. Angular js client side pagination like google.

2. Angular Loader using font awesome icons

3. Angular js add class to active element


Sunday, 25 October 2015

Angular select all/de select all checkbox

Let us check how we can make select/deselect check box using angular js. I have explained the same using Angular 2 and Jquery as well. If you want to compare the implementation please check below post as well.

1. Select all/ deselect all checkbox - Angular 2
2. Select all/ deselect all check box using Jquery

HTML



<input type="checkbox" ng-model="master" ng-change="isSelectAll()">
<label>Countries</label>

<span ng-repeat="label in labelList">
 <input type="checkbox" ng-model="label.selected" ng-change="isLabelChecked()">
 <label>{{ label.name }}</label>
</span>
 

JSON


 $scope.labelList = [
 {name:'India'},
 {name:'USA'},
 {name:'Russia'},
 {name:'China'},
 {name:'Australia'},
 {name:'Japan'}
 ]

Select all deselect all angular code



$scope.model = {
   selectedLabelList : []
}
$scope.isSelectAll = function(){
 
  $scope.model.selectedLabelList = [];
  
  if($scope.master){
    $scope.master = true;
    for(var i=0;i<$scope.labelList.length;i++){
     $scope.model.selectedLabelList.push($scope.labelList[i].name);  
    }
  }
  else{
   $scope.master = false;
  }
  
  angular.forEach($scope.labelList, function (item) {
    item.selected = $scope.master;
  });
}


Now you can see that select all/de select all feature is working fine .But if we unselect one of the checkbox then the master check box also need to uncheck and also if we select all check box master should also checked .For making this possible add below code as well.



$scope.isLabelChecked = function()
{
  var _name = this.label.name;
  if(this.label.selected){
   $scope.model.selectedLabelList.push(_name);
   if($scope.model.selectedLabelList.length == $scope.labelList.length )
    {
     $scope.master = true;
    }
  }else{
   $scope.master = false;
   var index = $scope.model.selectedLabelList.indexOf(_name);
   $scope.model.selectedLabelList.splice(index, 1);
 }
}
  

Another Approach

Comparatively better approach suggested by TIM in the comment section.

HTML


<div>
  <ul ng-controller="checkboxController">
    <li>
      <label>Countries
        <input type="checkbox" ng-model="selectedAll" ng-click="selectAll()" />
      </label>
    </li>
    <li ng-repeat="item in Items">
      <label>
        <input type="checkbox" ng-model="item.Selected" ng-click="checkIfAllSelected()" /> 
  {{item.name}}
      </label>
    </li>
  </ul>
</div>


JS



  $scope.Items = [{
      name: 'India'
    }, {
      name: 'USA'
    }, {
      name: 'Russia'
    }, {
      name: 'China'
    }, {
      name: 'Australia'
    }, {
      name: 'Japan'
    }];

    $scope.selectAll = function() {
      angular.forEach($scope.Items, function(item) {
        item.Selected = $scope.selectedAll;
      });
    };

    $scope.checkIfAllSelected = function() {
      $scope.selectedAll = $scope.Items.every(function(item) {
        return item.Selected == true
      })
    };


Related Posts

1. Angular js client side pagination like google.

2. Angular Loader using font awesome icons

3. Angular js add class to active element


Saturday, 27 June 2015

Dynamically load css and javascript

We can load css and javascript files dynamically using jquery/Javascript

Load javascript files using jquery


  var j = document.createElement('script');
  j.type = 'text/javascript';
  j.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js';
  document.getElementsByTagName('head')[0].appendChild(j);

Load Jquery if it is not loaded


 if ( typeof( jQuery ) == 'undefined' ){
  var j = document.createElement('script');
  j.type = 'text/javascript';
  j.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js';
  document.getElementsByTagName('head')[0].appendChild(j);
 }

Load CSS using jquery


 var ls = document.createElement('link'),
 ls.rel="stylesheet';
 ls.href= 'youcss.css";
 document.getElementsByTagName('head')[0].appendChild(ls);

Load css if not loaded already


 var links = document.getElementsByTagName('link'),
 needCSS = true;
 for ( var i = 0; i < links.length; i++ )
 {
  if ( links[i].href == "yourcss.css" ) 
  needCSS = false;
 }
 if ( needCSS )
 {
  var ls = document.createElement('link');
  ls.rel="stylesheet";
  ls.href="yourcss.css";
  document.getElementsByTagName('head')[0].appendChild(ls);
}

Related Posts

1. Covert string to camel case using javascript.

2. How to remove duplicate from an array and get count of duplicated .

3. Angular js add class to active element


Sunday, 26 April 2015

Angular js basic search and filter data with example

Angular js providing a very easy way to implement basic search and filter data using very less of code. I have tried same using Angular 2 as well. If anyone want to compare both implementation please check this as well Simple search using pipe in angular 2.

View

 
<div ng-repeat="datalist in datalists | filter:searchquery">
 <span>Name : {{ datalist.name }}</span>
 <span>Age : {{ datalist.age }}</span>
 <span>Age : {{ datalist.Designation }}</span>
</div>
 

Your filter text box

 

 <input type="text"  value="Search" ng-model="searchquery">
 
 

Note : We are assigning ng-model = "searchquery" to the filter text box .This is the only thing we have to do for filtering the data.

JSON

 
$scope.datalists = [
    { "name": "John","age":"16","Designation":"SW"},
    {"name": "Abraham","age":"21","Designation":"SW1"},
    {"name": "Norm","age":"19","Designation":"SW2"},
    {"name": "Leo","age":"17","Designation":"SW3"},
    {"name": "Christino","age":"21","Designation":"SW4"},
    {"name": "Prash","age":"31","Designation":"SW5"},
    {"name": "Saniya","age":"41","Designation":"SW6"},
 {"name": "Vinoj","age":"41","Designation":"SW6"}
    ]
 

Fiddle

Working Demo

Let us take another example .By using the same concept we can filter the data very easily without doing any additional code .Suppose you want to show only the data of people having age 21 ,you can do that filter concept very easily in the view .

Example of those have age 21

 
<div ng-repeat="datalist in datalists | filter:{age:'21'}">
 <span>Name : {{ datalist.name }}</span>
 <span>Age : {{ datalist.age }}</span>
 <span>Age : {{ datalist.Designation }}</span>
</div>
 

Example of those have age 41

 
<div ng-repeat="datalist in datalists | filter:{age:'41'}">
 <span>Name : {{ datalist.name }}</span>
 <span>Age : {{ datalist.age }}</span>
 <span>Age : {{ datalist.Designation }}</span>
</div>
 

If you are facing any issues with quotation ( '21') , you can try filter:{category:&quot;21&quot;}

Fiddle

Working Demo

Related Posts

1. Date filtering and formatting in Angular js.

2. Communicate with controllers in angular js

3. Rating Stars using angular js Directive concept

4. Angular routing

5. Loop concept in angular js



Thursday, 23 April 2015

Get url parameter using angular js

Using $location.search() you can easily get the query parameter.

I have written the same using Angular 2(+) concept as well, check these links for that Get Url parameter using Angular 4 and 3 simple ways to share data through angular route.

For example


 //url
 http://www.sample.com/#/?username='samplename'&tocken='tocken'
 //Note '#/'
 
 //In your controller 
 
 $location.search();
 
 Result:
 {
 username : 'samplename',
 tocken:'tocken'
 }
 
 

Even you can try ,


$location.search().username 
$location.search().tocken 

//you can write your own logic 

if($location.search().username && $location.search().tocken){
 //do your logic
}

 

Check query parameter is existing


  if($location.search().yourQueryData.indexOf('?') > 0)
  {
 //query parameter existing 
  }
  else{
 //no
  }

Related Posts

1. Angular js client side pagination like google.

2. Angular Loader using font awesome icons

3. Angular js add class to active element


Sunday, 19 April 2015

Covert string to camel case using javascript

It is very easy to do using css


.className 
{
  text-transform:capitalize;
}

But sometimes we have to take care this by using javascript .There are many ways to accomplish this , see the example below


var myLabel = "sample text example"

var split = myLabel.split(' ');

//iterate through each of the "words" and capitalize them
for (var i = 0, len = split.length; i < len; i++) {
 split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
}

myLabel= split.join(' ');

//your result
console.log(myLabel); //Sample Text Example


Related Posts

1. How to remove duplicate from an array and get count of duplicated .

2. Save Google map as binary image

3. Top 10 professional bloggers in India - 2014

4. Auto complete using html5

5. Dynamic height for side bar


Sunday, 22 March 2015

Angular switch statement

Using angular switch statement it is easy to implement logic in view itself.

Example 1



$scope.data = data; // json or backend data
<div ng-switch="data.status">
 <span ng-switch-when="C">Initializing</span>
 <span ng-switch-when="J">Loading</span>
 <span ng-switch-when="R">Creating</span>
 <span ng-switch-when="D">Success</span>
 <span ng-switch-when="P">Failed</span>
</div>

Here data.status equal to 'C' then UI will show "initializing" and respectively.

Related Posts

1. Angular js client side pagination like google.

2. Angular Loader using font awesome icons

3. Angular js add class to active element


Saturday, 21 March 2015

File upload and sending data to backend using angular js

Here we are going to discuss about uploading a file and sending to backend.


Html


<form name="upload" class="form" data-ng-submit="addFile()">
  <input type="file" name="file" multiple 
 onchange="angular.element(this).scope().uploadedFile(this)" />
 <button type="submit">Upload </button>
</form>

Controller


$scope.uploadedFile = function(element) {
 $scope.$apply(function($scope) {
   $scope.files = element.files;         
 });
}

Here uploadservice is nothing but my factory file .AS per MVC standard it would be good handling all data manipulation in factory file or service file.


$scope.addFile = function() {
 UploadService.uploadfile($scope.files,
   function( msg ) // success
   {
    console.log('uploaded');
   },
   function( msg ) // error
   {
    console.log('error');
   });
}

Factory file



uploadfile : function(files,success,error){
 
 var url = 'your web service url';

 for ( var i = 0; i < files.length; i++)
 {
  var fd = new FormData();
 
  fd.append("file", files[i]);
 
  $http.post(url, fd, {
  
   withCredentials : false,
  
   headers : {
    'Content-Type' : undefined
   },
 transformRequest : angular.identity

 })
 .success(function(data)
 {
  console.log(data);
 })
 .error(function(data)
 {
  console.log(data);
 });
}
}

Your file is successfully uploaded

Upload a file and send data and file to backend


If you want to send data along with file upload you can try below code .There is a slight change while sending data


uploadfile : function( files,success, error )
{

 var fd = new FormData();

 var url = 'your web service url';

 angular.forEach(files,function(file){
 fd.append('file',file);
 });

 //sample data
 var data ={
  name : name,
  type : type
 };

 fd.append("data", JSON.stringify(data));

 $http.post(url, fd, {
  withCredentials : false,
  headers : {
  'Content-Type' : undefined
  },
  transformRequest : angular.identity
 })
 .success(function(data)
 {
  console.log(data);
 })
 .error(function(data)
 {
  console.log(data);
 });
},



Related Posts

1. How to download file from backend to UI

2. Communicate with controllers in angular js

3. Rating Stars using angular js Directive concept

4. Angular routing

5. Loop concept in angular js

6. Filtering concept in angular js

7. Auto complete using html5


Friday, 13 March 2015

How to remove duplicate from an array and get count of duplicated .

Using very minimum code we can achieve this.

Sample json data

 
var data = [
    {
        name : 'John'
        age:'60'
    },
    {
        name : 'John'
        age:'60'
    },
    {
        name : 'John'
        age:'60'
    },
    {
        name : 'John'
        age:'60'
    },
    {
        name : 'Prakash'
        age:'60'
    },
    {
        name : 'Johnson'
        age:'60'
    },
    {
        name : 'Martha'
        age:'60'
    },

]


Jquery

 

var counts = [];
   jQuery.each(data, function(key,value) {
     if (!counts.hasOwnProperty(value.name)) {
  counts[value.name] = 1;
   } else {
  counts[value.name]++;
   }
 });
 

Do a console.log(counts) you can see duplicated names and count .If you want in an array format you can try below one

 

var finalResults = [];
     for(var cntVal in counts) {
  finalResults.push([cntVal, counts[cntVal]]);
}
 

Demo

Related Posts

1. Create responsive highchart

2. About CK-Editor

3. Dynamic height for side bar


Sunday, 25 May 2014

Auto complete in Angular js

There are lot of examples are available on google for doing autocomplete. But the default angular js auto complete ( typeahead ) has some disadvantages. So I am going to discuss here about how to customize angular typeahead directive.

I have used angular js 1.2 ,angular-strap 0.7 js and twitter bootstrap .



<input type="text" class="autosuggesttextbox" bs-typeahead="datalists" >

 



$scope.datalists = data;

 

So our autocomplete is ready .Here you can see that it forces user to select default option or has to press esc key .It is not user friendly.

How to solve this issue



$.fn.typeahead.Constructor.prototype.render = function(items) {
    var that = this;
    items = $(items).map(function (i, item) {
      i = $(that.options.item).attr('data-value', item);
      i.find('a').html(that.highlighter(item));
      return i[0];
    });

    this.$menu.html(items);
    return this;
};

 

Now you can see it removed the default selection.

Now it is almost similar to google auto suggest .But you can see if you type something on the text box and hit enter key it will vanish .If you have a separate button it will work fine. But on enter key if you are not selecting any suggested options and auto complete box is available it assumes that the value is undefined. We can override this issue by customizing the angular strap directive.Go to angular strap.js and copy typeahead directive and rename to typeaheadcustomized ( or any name ).



angular.module('$strap.directives').directive('bsTypeaheadnew', [
'$parse',
function ($parse) {
return {
  restrict: 'A',
  require: '?ngModel',
  link: function postLink(scope, element, attrs, controller) {
 var getter = $parse(attrs.bsTypeaheadnew), setter = getter.assign,
 value = getter(scope);
 scope.$watch(attrs.bsTypeaheadnew, function (newValue, oldValue) {
   if (newValue !== oldValue) {
  value = newValue;
   }
 });
 element.attr('data-provide', 'typeahead');
 element.typeahead({
   source: function (query) {
  return angular.isFunction(value) ? value.apply(null, arguments)
  : value;
   },
   minLength: attrs.minLength || 1,
   items: attrs.items,
   updater: function (value) {
  if (controller) {
    scope.$apply(function () {
   if( !angular.isDefined(value)){
      value = $('.autosuggesttextbox').val();
     }
     controller.$setViewValue(value);
    });
  }
  scope.$emit('typeahead-updated', value);
  return value;
   }
 });
 var typeahead = element.data('typeahead');
 typeahead.lookup = function (ev) {
   var items;
   this.query = this.$element.val() || '';
   if (this.query.length < this.options.minLength) {
  return this.shown ? this.hide() : this;
   }
   items = $.isFunction(this.source) ? this.source(this.query,
   $.proxy(this.process, this)) : this.source;
   return items ? this.process(items) : this;
 };
 if (!!attrs.matchAll) {
   typeahead.matcher = function (item) {
  return true;
   };
 }
 if (attrs.minLength === '0') {
   setTimeout(function () {
  element.on('focus', function () {
    element.val().length === 0 && setTimeout(element.typeahead
    .bind(element, 'lookup'), 200);
  });
   });
 }
  }
};
}
]);

 

What we have done here is that we rename bs-typeahead to bs-typeaheadnew and added this if else condition



if( !angular.isDefined(value)){
  value = $('.autosuggesttextbox').val();
}


 

If value is undefined it will select from the text box

You can add min-length="2" to your text box for specifying when it should show auto complete.



<input type="text" class="autosuggesttextbox" min-length="2"
 bs-typeahead="datalists" >


 

References

1. Angular js

2. Angulat strap1.0

3. Angulat strap2.0.2

Related Posts

1. Communicate with controllers in angular js

2. Rating Stars using angular js Directive concept

3. Angular routing

4. Loop concept in angular js

5. Filtering concept in angular js

6. Auto complete using html5


Saturday, 24 May 2014

Submit form on enter click – Angular js

It is very easy to achieve this in angular js .We can check with one example. Suppose you have one text box inside the form and want to submit on enter key here is the way.

 

<form name="name" class="form" ng-submit="submitform()">

 <input type="text" ng-model="model.term"/>
 
 <button type="submit" class="btn">
  Submit
 </button>

</form>


What we have done is that just defined our function in ng-submit. It will work perfectly but there are some situations we have to deal with multiple text box and have to submit on enter .In that case you can define simple directive and you can add your function on ng-enter .

Lets check with another example .

 

<input type="text" ng-enter="submifunction1();" ng-model="model.term1"/>

<input type="text" ng-enter="submifunction2();" ng-model="model.term2"/>

<input type="text" ng-enter="submifunction3();" ng-model="model.term3"/>
 

Directive

 

angular.module('yourmodule').directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                    scope.$eval(attrs.ngEnter);
                });
 
                event.preventDefault();
            }
        });
    };
});

 

Related Posts

1. Angular routing

2. Rating Stars using angular js Directive concept

3. Communication between factory file and controller in Angular js

4. Communicate with controllers in angular js

5.Client side pagination using angular js


Saturday, 17 May 2014

Save google map as binary image

There are some situations we have to save google map as an image. It is always better to convert as a binary image and save to DB so that we can reuse very easily.

Here we are plotting the google map


 <div id="googlemap"></div>

Here we are displaying the converted binary image


 
 <div id="googlemapimage">
 <img id="googlemapbinary"/>
 </div>

 

Let us check the code now



function convertasbinaryimage()
{ 
html2canvas(document.getElementById("googlemap"), {

useCORS: true,

onrendered: function(canvas) {
     
 var img = canvas.toDataURL("image/png"); 
   
 img = img.replace('data:image/png;base64,', '');
 
 var finalImageSrc = 'data:image/png;base64,' + img;
 
 $('#googlemapbinary').attr('src', finalImageSrc);                    
 
 return false;                    
}
});
}
 

What I have done is that, I used html2canvas plugin support and then converting to binary image .Now you can take this html or binary code and can save to DB

Don't forget to add html2canvas plugin


http://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js

References

1. html2canvas

2. Google Map Api

Related Posts

1. Save high chart as binary image

2. Responsive high chart

3. Integration of CK-Editor to ui

4. Dynamic height for side bar

5. Auto complete using html5


Friday, 9 May 2014

Set headers for all $http calls in angular js

Angular js providing an option to set a common headers for all $http calls (get, post etc).

This is very important as part of security, we have to use a authentication token or id that is getting while logging into the application. It is not easy to set authentication id or token manually for all $http calls .So we can attach a common header for all $http calls so that service can read that while making all calls so that application will be more secure .

I have explained same using Angular 4 concept as well, check this link for that.

There are many ways .

1. Set on $http

2. Using interceptor concept

3. Only for particular $http calls

1. Set on $http


angular.module('yourmodule').run(function($http) {
  
  $http.defaults.headers.common.Authorization = 'login YmVlcDpi' ;
  //or try this
  $http.defaults.headers.common['Auth-Token'] = 'login YmVlcDpi';

});

We can check with a real scenario.


$rootScope.user = { username: model.username, authenticationid:id};
//Setting Cookie
$cookieStore.put( 'yourmodule', $rootScope.user );

Here I am saving username and authentication id to a cookie (you can use session also).


var id = $rootScope.user.authenticationid ;

angular.module('yourmodule').run(function($http) {
  
  $http.defaults.headers.common.Authorization = id ;
  //or try this 
  $http.defaults.headers.common['Auth-Token'] = id;
 
});

Now check in the network or console you can see all $http calls have the common header.

2. Using interceptor concept


angular.module('yourmodule').factory('httpRequestInterceptor',
['$rootScope', function($rootScope)
 {
  return {
   request: function($config) {
    if( $rootScope.user.loginticket )
    {
     $config.headers['your-auth-ticket'] = $rootScope.user.loginticket;
    }
  return $config;
  }
 };
}]);
 

Add this into app config .


$httpProvider.interceptors.push('httpRequestInterceptor');
 

3. Only for particular $http calls


 var data = {
    somedata :data.data
  };
 var url = 'your webservcie url';
 
 $http.post(url,angular.toJson(data),{
 headers: {'login_token': 'login YmVlcDpi'}
 })
 .success( function( data )
 {
    success(data);
 })
 .error( function( data)
 {
   error(data);
 });

Related Posts

1. Angular routing

2. Rating Stars using angular js Directive concept

3. Communication between factory file and controller in Angular js

4. Communicate with controllers in angular js

5. Client side pagination using angular js


Sunday, 4 May 2014

Top 10 professional bloggers in India

Last updated : 12 11 2017

Without bloggers internet is nothing. Blogging is not yet a common profession in India but there are some people who chose blogging as their profession.


Here is the list of professional bloggers in India and their approximate earnings per month.

1. AMIT AGARWAL

Blog : Labnol.org

Subject : Technology

Twitter : @labnol

Income : $50000 / Month

2. HARSH AGARWAL

Blog : Shoutmeloud.com

Subject : Blogging

Twitter : @ShoutMeLoud

Income : $10000 / Month

3. IMRAN UDDIN

Blog : alltechbuzz.net

Subject : Blogging , SEO

Twitter : @Imran_atb

Income : $8000 / Month

4. VARUN KRISHNAN

Blog : fonearena.com

Subject : Smartphones

Twitter : @varunkrishl

Income : $10000 / Month

5. ASHISH SINHA

Blog : nextbigwhat.com

Subject : Entrepreneurship

Twitter : @cnhal

Income : $6000 / Month

6. SHRADHA SHARMA

Blog : yourstory.com

Subject : Entrepreneurship

Twitter : @sharmasharadhal

Income : $5000 / Month

7. AMIT BHAWANI

Blog : androidadvices.com

Subject : Android

Twitter : @amitbhawani

Income : $10000 / Month

8. SRINIVAS TAMADA

Blog : 9lessons.info

Subject : Technical

Twitter : @9lessons

Income : $5000 / Month

9. ARUN PRABHUUDESAI

Blog : track.in

Subject : Technology

Twitter : @8ap

Income : $3000 / Month

10. KULWANT NAGI

Blog : bloggingcage.com

Subject : Blogging

Twitter : @kulwantnagi

Income : $2000 / Month

There may be so many unknown bloggers who is earning more than this.And these are based on an approximate calculations.


Saturday, 3 May 2014

Angular js Cookies

Here I am going to explain about how to store login credentials into angular cookies.


angular.module('yourmodule').factory('LoginService',
function( $rootScope, $http, $cookieStore)
{

$rootScope.user = { username: model.username, role: role};

//Set Cookie
$cookieStore.put( 'yourmodule', $rootScope.user );

});


$rootScope is global and you can use anywhere in your module

For getting user name in any controller in the same module



var username = $rootScope.user.username ;

var role = $rootScope.user.role ;


Destroy cookie

For destroying cookies on log out add this simple code on your log out functionality.



$cookieStore.remove('yourmodule');

$rootScope.user = { username: '', role: 0 };


Related Posts

1. Save highchart as binary image

2. Communicate with controllers in angular js

3. Angular routing

4. Rating Stars using angular js Directive concept

5. Loop concept in angular js

6. Filtering concept in angular js