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