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


Wednesday, 30 April 2014

Auto complete using html5

We can do autocomplete Using jQuery or any other scripting language, but required some line of codes .It is very simple to do autocomplete using HTML5.HTML5 introduced a new tag datalist, this will do the trick.Let us check with a small example.

HTML


<input type="text" list="countries" name="country" />

<datalist id="countries">
 <option value="India">
 <option value="Albania">
 <option value="United Kingdom">
 <option value="United States">
 <option value="Australia">
 <option value="China">
 <option value="England">
 <option value="Zambia">
 <option value="Zimbabwe">
</datalist>


Working Demo

Sad thing is that some browsers are not started yet to support datalist tag.So far IE 10 and above, Firefox, Chrome and Opera 19 above supports html5 datalist tag. Safari doesn’t support datalist yet. But still you can be clever in those kind of browsers .For example

HTML


<input type="text" list="countries" name="country" />

<datalist id="countries">
<label>or select a country from list:</label>
  <select>
 <option value="India">
 <option value="Albania">
 <option value="United Kingdom">
 <option value="United States">
 <option value="Australia">
 <option value="China">
 <option value="England">
 <option value="Zambia">
 <option value="Zimbabwe">
 </select>
</datalist>


Open in safari and other browsers to see the result

Working Demo

Related Posts

1. Create responsive highchart

2. About CK-Editor

3. Dynamic height for side bar

4. Auto complete in Angular js


Monday, 28 April 2014

Angular js client side pagination like google.

Here we read about simple angular js client side pagination, now it’s time to do advanced client side pagination. Here i am going to explain about Pagination like google using angular js client side logic. First load all data to UI.

View

Here datalist is the data you are getting from service (backend).


<ul>
<li class="paginationclass" ng-repeat="datalist in datalists 
| pagination : currentPage*itemsPerPage | limitTo: itemsPerPage">
 
 <div>
 <span> Name : {{ datalist.name }}</span>
 <span> Age : {{ datalist.age }}</span>
 <span> Designation : {{ datalist.Designation }}</span>
 </div> 
</li>
</ul> 

Pagination div



<div class="pagination-div">
 
 <ul class="pagination">
  
  <li ng-class="DisablePrevPage()">
  
  <a href ng-click="prevPage()"> Prev</a>
  
  </li>
  
  <li ng-repeat="n in range()" 
  
  ng-class="{active: n == currentPage}"
  
  ng-click="setPage(n)">
  
  <a href="#">{{n+1}}</a>
  
  </li>
  
  <li ng-class="DisableNextPage()">
  
  <a href ng-click="nextPage()">Next </a>
  
  </li>
 
 </ul>

</div>


Controller

Here datalist is the data you are getting from service (backend).


 
 $scope.itemsPerPage = 5;
 
 $scope.currentPage = 0;
 
 $scope.datalists = data ;// Service
 
 

 

$scope.range = function() {

 var rangeSize = 4;

 var ps = [];

 var start;

 start = $scope.currentPage;

 if ( start > $scope.pageCount()-rangeSize ) {

  start = $scope.pageCount()-rangeSize+1;

  }

 for (var i=start; i<start+rangeSize; i++) {

 ps.push(i);

}

return ps;

};


$scope.prevPage = function() {

if ($scope.currentPage > 0) {

$scope.currentPage--;

}
};


$scope.DisablePrevPage = function() {

return $scope.currentPage === 0 ? "disabled" : "";

};


$scope.pageCount = function() {

return Math.ceil($scope.datalists.length/$scope.itemsPerPage)-1;

};


$scope.nextPage = function() {

if ($scope.currentPage > $scope.pageCount()) {

$scope.currentPage++;

}
};


$scope.DisableNextPage = function() {

return $scope.currentPage === $scope.pageCount() ? "disabled" : "";

};


$scope.setPage = function(n) {

$scope.currentPage = n;

};

Add all of these in your controller

Filter

You can declare this in filter.js or controller itself or in directive.


angular.module('sampleapp').filter('pagination', function()
{
  return function(input, start) {
    start = parseInt(start, 10);
    return input.slice(start);
  };
});


Working Demo

As TomALex mentioned in the comment "i noticed is if you set "itemsPerPage" to 300, we will see -2,-1,0 in pagination."

For that fix , please refer this updated fiddle

Updated Fiddle

The fix was - Add a check before pushing 'i' in $scope.range function



for (var i=start; i<start+rangeSize; i++) {
     if(i>=0) 
        ps.push(i);
    }


 

1. Angular js simple client side pagination

2. Angular js simple show more pagination

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


Sunday, 27 April 2014

Angular Loader using font awesome icons

Font Awesome gives you scalable vector icons that can instantly be customized — size, color, drop shadow, and anything that can be done with the power of CSS. You can improve the performance of your site by using font awesome images.
Click here to Download Font Awesome


Loading bar gives a better user experience .It is always better to show loading bars to users while doing saving or any other action it took some time. We can give very nice experience for users by using font awesome icons with angular js.

HTML

" fa fa-spinner fa-spin " are font awesome icon classes.

 

<button class="btn btn-primary">
 
 <span data-ng-hide="loading">
 Save 
 </span>
 
 <span data-ng-show="loading">
 Saving
 <i class="fa fa-spinner fa-spin"></i>
 </span>

</button>           

 
 

Controller

 

 //False on page load
 $scope.loading = false ; 

$scope.onSubmit = function(){

 $scope.loading = true ; 

}


After getting the success response from service (backend) change loader status to false.

Fiddle

Working Demo

Related Posts

1. Angular ng-repeate in directive

2. Loop concept in angular js

3. Angular js client side show more pagination

4. Show and Hide in angular

5. Simple client side sorting in angular


Saturday, 26 April 2014

Angular delete rest service

There is a slight difference in the syntax of angular delete as compared to post and get method.

Angular Delete



deleteData : function(success, failure) {

var url = 'your webservice ';    

$http['delete'](url)

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


Angular Post



postData : function( data ,success, failure) {

var url = 'Your webservice';

var data = {
 "data" :data 
};

$http.post(url, angular.toJson(data))

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



Angular Get



getData : function( success, failure)
{

var url = 'Your webservice';

$http.get( url, {cache: false} )

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



Angular Put



put: function( data, success, error )
{

var _url = 'your webservice';

$http.put( _url, angular.toJson(data), {cache: false} )
 
 .success( function( response )
 {
  console.log(data);
 })
 .error( function( response )
 {
  console.log(data);
 }
);
}




For better understanding



Angular DELETE

$http['delete'](url)

Angular POST

$http.post(url, angular.toJson(data))

Angular GET

$http.get( url, {cache: false} )

Angular PUT

$http.put( _url, angular.toJson(data), {cache: false} )


Related Posts

1. Communication between factory file and controller in Angular js

2. Communicate with controllers in angular js

3. Rating Stars using angular js Directive concept

4. Angular ng-repeate in directive


Friday, 25 April 2014

Dynamic height for side bar

We can achieve this by using simple jQuery or plain css.

1. Using Jquery

We can do this by very easily with the help of a simple jQuery .In this example I used sticky footer

HTML


<div class="header">Header</div>
<div class="sidebar">Side Bar</div>
<div class="middlecontent">Content</div>
<div class="footer">Footer</div>

Jquery


$(document).ready(function(){
   
   var dynamic = $(document).height();
 
 var static = $('.sidebar');    
    
 static.css({
  'min-height': dynamic,
  'max-height': dynamic
  });
});
  

Play in fiddle

Demo

2. Using CSS

In this method not required any jQuery or JavaScript only simple css.

HTML


<div class="wrapper">
<div class="sidebar"></div>
<div class="content">Content</div>

CSS


.wrapper
    {
        min-height:100%;
        width:100%;
        position:relative;
        display:inline-block;
    }
    .sidebar
    {
        width:20%;
        top:0px;
        left:0px;
        bottom:0px;
        position:absolute;
        background-color:yellow;
    }
    .content
    {
        min-height:300px;
        width:80%;
        position:relative;
        background-color:#CCC;
        float:right;
    
    }  

Play in fiddle

Demo

Related Posts

1. Create responsive highchart

2. About CK-Editor

3. Auto complete using html5


Thursday, 17 April 2014

Angular js add class to active element

Here I am going to explain how to add active class on dynamically added content or link while on clicking. I have explained same using Angular 2/4 concept as well check this link for that.

View

 
<ul>

<li ng-repeat="datalist in datalists" ng-click="select(datalist)"
                 
  ng-class="{active: isActive(datalist)}" >

 <div>{{ datalist.name }}</div> 

 </li>

 </ul> 
        
 

Controller

 

 $scope.select= function(item) {
        $scope.selected = item; 
 };

 $scope.isActive = function(item) {
        return $scope.selected === item;
 };

 
 

Click on any link, active class will be added to the active element.

Demo

Play in fiddle

But if we need to remove the active class on clicking the item again.Refer this post Add and remove active class on click Angular

Related Posts

1. Angular ng-repeate in directive

2. Loop concept in angular js

3. Angular js client side show more pagination

4. Show and Hide in angular

5. Simple client side sorting in angular

6. Add and remove active class on click Angular

7. Add a class for everything clicked - angular

8. Toggle click on dynamic menu items - Angular


Angular js client side show more pagination

Angular js providing a very easy way to do client side pagination. Here i am going to explain about simple client side show more pagination using angular js.

I have written the same using Angular 2(+) concept as well - show more/less pagination using Angular 2(+)

View

 
<ul>

<li ng-repeat="datalist in datalists | limitTo: paginationLimit()">

 <div>Name : {{ datalist.name }} Age : {{ datalist.age }}</div> 

 </li>

 </ul> 
        
<div>
 
 <button ng-show="hasMoreItemsToShow()" ng-click="showMoreItems()">
      Show more
 </button>

 </div>
 
 

Controller

 
$scope.datalists = data // json data

//show more functionality

var pagesShown = 1;

var pageSize = 3;

$scope.paginationLimit = function(data) {
 return pageSize * pagesShown;
};

$scope.hasMoreItemsToShow = function() {
 return pagesShown < ($scope.datalists.length / pageSize);
};

$scope.showMoreItems = function() {
 pagesShown = pagesShown + 1;       
}; 

 
 

$scope.datalist is nothing but the json you are getting from backend (Service).We are looping the data into view.

Demo

Play in fiddle

1. Angular js client side pagination like Google

2. Angular js simple client side pagination

Related Posts

1. Angular ng-repeate in directive

2. Loop concept in angular js

3. Filtering concept in angular js

4. Show and Hide in angular

5. Simple client side sorting in angular


Wednesday, 16 April 2014

Angular js auto focus for input box

Create a directive for autofocus and use where ever you need on the module.

I have explained the same using Angular 2/5 concept as well, for that please check this link:- Angular autofocus for input box - Angular 2/5.

Directive

 
 
// Common directive for Focus

angular.module('sampleapp').directive('focus',
function($timeout) {
 return {
 scope : {
   trigger : '@focus'
 },
 link : function(scope, element) {
  scope.$watch('trigger', function(value) {
    if (value === "true") {
      $timeout(function() {
       element[0].focus();
      });
   }
 });
 }
};
}); 
    
 

View

 
 
    Auto Focus : <input type="text" focus="true">

 

Demo

Play in fiddle

Related Posts

1. Angular ng-repeate in directive

2. Loop concept in angular js

3. Filtering concept in angular js

4. Show and Hide in angular

5. Simple client side sorting in angular


Tuesday, 15 April 2014

Angular js client side sorting

Angular js is providing a very easy way to do client side sorting. Here I am going to explain about a simple client side sorting.

View

 
 
<select ng-model="sortorder1">
 
 <option disabled value="">Choose one</option>
 
 <option value="name">Name</option>     
 
 <option value="age">Age</option>

 </select>        
        
<ul>
 
 <li ng-repeat="datalist in datalists | orderBy:sortorder1">
 
 <div>Name : {{ datalist.name }} Age : {{ datalist.age }}</div> 
 
 </li>

 </ul>

    
 

Here datalist is the json data ( $scope.datalists = data ;)

Demo

Play in fiddle

Related Posts

1. Angular ng-repeate in directive

2. Loop concept in angular js

3. Filtering concept in angular js

4. Show and Hide in angular


Sunday, 13 April 2014

Show and hide in Angular js

Using jquery we can do this by $('.loader').hide(); or $('.loader').show();.But as we are using angular js in our application this not a best coding practice, we should do in angular way .And one of the advantage of using angular js is no need to depend on html id or class .So our functionality has no dependency on id or class.

View

 
 
<div ng-show="loader.loading">Loading...</div>
 
 

Controller

 
 
$scope.loader = {
 loading: false,
 };
 
$scope.someFunction = function( )
{
 
 $scope.loader.loading = true ;
 
 var _url = 'your service url';
 
 var data = {
   name: name
 };
 
 $http.post( _url, angular.toJson(data), {cache: false} )
  .success( function( data )
  {
   
   console.log(data);
   
   $scope.loader.loading = false ;
  
  })
  .error(function(data){
   
   error(data);
 
 });
 
};
 
 

Fiddle

Working Demo

Another advantage is we can show and hide with multiple conditions very easily .

View

 
 
<h4 ng-show="state == 'LOADING'">Loading...</h4>
<h4 ng-show="state == 'NORESULTS'">No results.</h4>
<h4 ng-show="state == 'SUCCESS'">Your result</h4>
    
 

Controller

 
 

$scope.someFunction = function( )
{
 
 $scope.state = "LOADING" ;
 
 var _url = 'your service url';
 
 var data = {
   name: name
 };
 
 $http.post( _url, angular.toJson(data), {cache: false} )
  .success( function( data )
  {
   
   console.log(data);
   
   if ( data.length <= 0 ){
   
    $scope.state = "NORESULTS" ;
   
   }
   else{
   
   $scope.state = "SUCCESS" ;
   
   }
  
  })
  .error(function(data){
   
   error(data);
 
 });
 
};
 
    
 

It is so simple than jquery and less coding for bigger applications and easy to maintain also .

Fiddle

Working Demo

Related Posts

1. Angular Loader using font awesome icons

2. Communication between factory file and controller in Angular js

3. Communicate with controllers in angular js

4. Rating Stars using angular js Directive concept

5. Angular ng-repeate in directive


Tuesday, 8 April 2014

Date filtering and formatting in Angular js.

Here I am going to explain about angular date filtering concept. It is always better to create a filter.js file for those filtering concept. Advantage of this is you can very easily filter the data anywhere in your view . I have written same using Angular 2+ concept as well, click here if interested .

View


 <span>{{ d.time | date }}</span>

Here "date" from filter.js and "d.time" is the time that we are going to filter ( From your controller or view ).

Filter.js


angular.module('yourmodule').filter('date', function($filter)
{
 return function(input)
 {
  if(input == null){ return ""; } 
 
  var _date = $filter('date')(new Date(input), 'MMM dd yyyy');
 
  return _date.toUpperCase();

 };
});

Even you can format date with some condition.


angular.module('yourmodule').filter('date', function($filter)
{
 return function(input)
 {
  if(input == null){ return ""; } 
 
  if( your condtion )
  {
   var _date = $filter('date')(new Date(input), 'MMM dd yyyy');
  }
  else {
    var _date = $filter('date')(new Date(input), 'MM dd yyyy');
  }
 
  return _date.toUpperCase();

 };
});

Time filtering



angular.module('yourmodule').filter('time', function($filter)
{
 return function(input)
 {
  if(input == null){ return ""; } 
 
  var _date = $filter('date')(new Date(input), 'HH:mm:ss');
 
  return _date.toUpperCase();

 };
});

View


 <span>{{ d.time | time }}</span>

Date time filtering



angular.module('yourmodule').filter('datetime', function($filter)
{
 return function(input)
 {
  if(input == null){ return ""; } 
 
  var _date = $filter('date')(new Date(input),
                              'MMM dd yyyy - HH:mm:ss');
 
  return _date.toUpperCase();

 };
});

View


 <span>{{ d.time | datetime }}</span>

Filter the data in controller



angular.module('sampleproject').controller( 'sampleController',
function ($rootScope, $scope,$filter )
{
 
 var filterdatetime = $filter('datetmUTC')( date );
or
 var filterdatetime = $filter('datetmUTC')( $scope.date );

});

Fiddle

Related Posts

1. Client side pagination using angular js

2. Angular flash message using directive

3. Angular routing

4. Rating Stars using angular js Directive concept

5. Filtering concept in Angular JS

6. Communicate with controllers in angular js


Saturday, 5 April 2014

Angular ng-repeat in directive

Here I am going to explain how to create a directive for displaying a dynamic content.

Directive

 
angular.module('samplemodule').directive('itemList',
function() {
return {
 restrict : "AC",
 template : '<div>'
  + '<div>{{ datalist.title }}</div>'
  + '<div>{{ datalist.content }}</div>'
  + '</div>',
 link : function(scope, elm, attrs) {
  scope.$watch(attrs.itemList, function(value) {
   elm.text(value);
  });
 }
};
}
);
 

Directives are markers on a DOM element that tell AngularJS's HTML compiler to attach a specified behavior to that DOM element or even transform the DOM element and its children. Better define all Global controllers in Directives. Ex: Warning message, alert etc.

'A' - Attribute (Use it as <div itemList>)

'E' - Element (Use it as <itemList>)

'C' - Class. (Use it as <div class="itemList">)

'M' - Comment (Use it as <!- directive: itemList -> )

We used watch concept in directive .Watch is a powerful feature of angular js. “$watch” concept in Angular is to observe the changes on the data of the scope from the controller. That is controller can add a listener on an attribute of its scope.

Controller

 
 
 $scope.datalist = data //  json from service
 
 

View

 
 
<div class="item-list:list" data-ng-repeat="datalist in datalists">
 
 

Related Posts

1. Client side pagination using angular js

2. Angular flash message using directive

3. Angular routing

4. Rating Stars using angular js Directive concept

5. Communication between factory file and controller in Angular js

6. Communicate with controllers in angular js


Monday, 31 March 2014

Value is not updating in IE-8 - Angular js

I have faced an issue while using angular service, that is value is not updating in IE-8

On click of add new button I am calling a rest service and displaying the response in a table. It has an edit option in each row , what is happening in IE-8 is that after saving edited data it is still showing the old data .It is working fine in all other browsers .

My code that is not working in IE-8

Most of the time i was not able to get the updated value in IE-8

 
getUsers: function(data, success, error)
{ 
 var url = var url = '/your web service path';;
 
 $http.get(url)
  .success(function(data, status)
  {
   success(data);
   
  })
  .error(function(data, status)
  {
   error(data);
   
  });
}

 

Code that worked in all browsers

I have changed this to below code and it started to works in IE-8 also.

 
getUsers: function(data, success, error)
{ 
var url = '/your web service path';

//Added this
var fetch_timestamp = function() { return parseInt
 (new Date().getTime().toString().substring(0, 10))};

// or  
// var currentTime = new Date().getTime();

var timestamp = fetch_timestamp();

url = url + '&t='+timestamp;

$http.get(url)
 .success(function(data, status)
 {
  success(data);
  
 })
 .error(function(data, status)
 {
  error(data);
  
 });
}

 

This piece of code fixed my issue.

 
var url = '/your web service path';

//Added this
var fetch_timestamp = function() { return parseInt
 (new Date().getTime().toString().substring(0, 10))};

// or  
// var currentTime = new Date().getTime();

var timestamp = fetch_timestamp();

url = url + '&t='+timestamp;
 

But I am not sure this will be the right fix .I thought to share this because it may help to somebody .If you are thinking this is a wrong fix please add a comment or give a referral link.

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


Thursday, 27 March 2014

Integration of CK-Editor to UI

Here I am going to explain how to integrate CK-Editor to UI , set the data to editor and how to remove some controls from CK-Editor. Minimum files required to integrate CK-Editor are CK-Editor.js, config.js, lang, plugins ( you can remove or add the plugin for your choice .For example smiley, special character, table etc.), skins, style.js .

You can download CK-Editor from here .

Controller

 
//Initialize the Editor
initEditor();

//Replace the <textarea id="editor1"> with an CKEditor instance.  
function initEditor()
{
CKEDITOR.replace( 'editor1', {

pluginsLoaded: function( evt ) 
{
 var doc = CKEDITOR.document, ed = evt.editor;
 if ( !ed.getCommand( 'bold' ) )
  doc.getById( 'exec-bold' ).hide();
 if ( !ed.getCommand( 'link' ) )
  doc.getById( 'exec-link' ).hide();
 }
  }
 });
}



View

 
<textarea cols="100"  id="editor1" name="editor1" rows="50">

</textarea>

How to set data to CK-Editor

For dynamic data you can try this

 
 CKEDITOR.instances['editor1'].setData(data);
   

Copying data to mouse pointer

For adding data to mouse pointer you can try this

 
 CKEDITOR.instances['editor1'].insertHtml( data ); 

While working with CK-Editor you may face issues like :-
Not displaying the data until we resize the Editor or Browser .In that case you can try this

 
 CKEDITOR.instances['editor1'].setData(data);

 CKEDITOR.instances.editor1.resize();


How to get data from CK-Editor

For taking data from editor you can try this

 
 $scope.data = CKEDITOR.instances.editor1.getData();

Remove some controls from CK-Editor

For removing some controls , open config.js

 
CKEDITOR.editorConfig = function( config ) {

// Define changes to default configuration here. For example:

// config.language = 'fr';

// config.uiColor = '#AADC6E';

 config.height = '96%';

 config.marginTop = '10px';

 config.removePlugins = 'save,a11yhelp,forms,etc';

 config.removeButtons = 'Styles,Anchor,Templates' ;

 config.resize_enabled = false;

};

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


Tuesday, 25 March 2014

Responsive Highchart

Highcharts is a very good option for creating Interactive javascript charts for your webpage. Highstock is an another advanced option of highstock. Highcharts currently supports line, spline, area, areaspline, column, bar, pie, scatter, angular gauges, arearange, areasplinerange, columnrange, bubble, box plot, error bars, funnel, waterfall and polar chart types.

HTML


<div id="chartcontainer" width='100%'></div>

Javascript


<script>
var chart1; // globally available
$(document).ready(function () {
chart1 = new Highcharts.Chart({
 chart: {
  renderTo: 'chartcontainer',
  type: 'column' // change with your choice
 },
 title: {
  text: 'Fruit Consumption'
 },
 xAxis: {
  categories: ['Apples', 'Bananas', 'Oranges'] 
  // Should be replace with JSON
 },
 yAxis: {
  title: {
   text: 'Fruit eaten'
  }
 },
 series: [{   //Should be replace with JSON
  name: 'Jane',
  data: [1, 0, 4]
 }, {
  name: 'John',
  data: [5, 7, 3]
 }]
});

});

</script>

Include highchart.js


<script src="http://code.highcharts.com/highcharts.js"></script>

Demo

Play in fiddle

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


Friday, 21 March 2014

Rating stars in angular js using directive

Here I am going to explain how to create rating feature using angular js directive concept and send the rating value to backend ( service ). I have explained same using Angular 2(+) concept as well, if you want to compare both implementation check this link as well.

Refer this link to know how it is implemented in Angular 2(+):- Rating star component using Angular 2(+).

Angular js 1 Directive


 
angular.module('samplemodule').directive('starRating',
function() {
return {
restrict : 'A',
template : '<ul class="rating">'
   + ' <li ng-repeat="star in stars" 
   ng-class="star" ng-click="toggle($index)">'
   + '  <i class="fa fa-star-o"></i>'
   + ' </li>'
   + '</ul>',
scope : {
 ratingValue : '=',
 max : '=',
 onRatingSelected : '&'
},
link : function(scope, elem, attrs) {
 var updateStars = function() {
  scope.stars = [];
  for ( var i = 0; i < scope.max; i++) {
   scope.stars.push({
    filled : i < scope.ratingValue
   });
  }
 };
 
 scope.toggle = function(index) {
  scope.ratingValue = index + 1;
  scope.onRatingSelected({
   rating : index + 1
  });
 };
 
 scope.$watch('ratingValue',
  function(oldVal, newVal) {
   if (newVal) {
    updateStars();
   }
  }
 );
}
};
}
);


Here i used Font awesome icon ( <i class="fa fa-star-o"></i> ).Font Awesome gives you scalable vector icons that can instantly be customized — size, color, drop shadow, and anything that can be done with the power of CSS.
Font awsome icons
You can improve the performance of your site by using font awesome images.

View

 
 
<div ng-init="rating = star.rating + 1"></div>

<div class="star-rating" star-rating rating-value="rating"

 data-max="10" on-rating-selected="rateFunction(rating)"></div>
 

Only for displaying the rating you can use the class as star-rating.Here i am going to explain how to send this rating to backend (Service).

Controller

 
    
$scope.rateFunction = function( rating )
{
       var _url = 'your service url';
 
 var data = {
   rating: rating
 };
 
 $http.post( _url, angular.toJson(data), {cache: false} )
  .success( function( data )
  {
   success(data);
  })
  .error(function(data){
    error(data);
  });
 
};
 
 

CSS

Using this "filled" class we are changing the color of the rated stars .

 

.rating .filled {
color: #21568b;
}

Demo

Play in fiddle

Directives are markers on a DOM element that tell AngularJS's HTML compiler to attach a specified behavior to that DOM element or even transform the DOM element and its children. Better define all Global controllers in Directives. Ex: Warning message, alert etc.

'A' - Attribute (Use it as <div starrating>)

'E' - Element (Use it as <starrating>)

'C' - Class. (Use it as <div class="starrating">)

'M' - Comment (Use it as <!- directive: starrating -> )

We used watch concept in directive .Watch is a powerful feature of angular js. “$watch” concept in Angular is to observe the changes on the data of the scope from the controller. That is controller can add a listener on an attribute of its scope.

Related Posts

1. Communicate with controllers in angular js

2. Angular routing

3. Loop concept in angular js

4. Filtering concept in angular js

5. Save highchart as binary image


Communicate with controllers in angular js

There are many ways to communicate with different controllers .Some of them are

1. Share data between controllers by making function as Global
2. Share data between controllers using factory file
3. Using $emit or $broadcast
4. Using Watch Concept.

1. Share data between controllers by making function as Global


We have one ng-click function in controller1 .Onclick of this we have to share a data to controller 2 and invoke another function.

Controller 1

 
 
angular.module('sampleproject').controller( 'Controller1',
function ($rootScope, $scope )
{
  $scope.shareData = function( data ){
  
  $scope.sampleFunction( data) ;
   
  };
}); 
 

Controller 2

 
 
angular.module('sampleproject').controller( 'Controller2',
function ($rootScope, $scope )
{
  $rootScope.sampleFunction = function( data ){
  
  console.log(data);
  // your logic
   
  };
}); 
 

Here we are making function as global using $rootScop .We can access this function anywhere in the module.

2. Share data between controllers using factory file .


The most common and recommended method for sharing data between controllers is to use a service. Make a factory file common for controllers .

View



<div ng-app="sampleApp">
    
 <div ng-controller="Ctrl1">Controller 1: {{foo}}</div>
    
 <div ng-controller="Ctrl2">Controller 2: {{foo}}</div>

</div>


Factory File



var app = angular.module('sampleApp', []);

app.factory('Service', function() {
 
 var Service = {
    foo: 'Shared service'
  };
 
 return Service;
});



Controller 1




app.controller('Ctrl1', function($scope, Service) {

  $scope.foo = Service.foo;

  Service.foo = 'I am from contoller 1';

  });


Here Service is the factory file name.

Controller 2



app.controller('Ctrl2', function($scope, Service) {
  
  $scope.foo = Service.foo;

});


Play in fiddle

3. Using $emit or $broadcast


You can communicate between controllers using $emit and $broadcast as well, check below example for that.


$scope.$emit('itemClicked', [_item]);
$rootScope.$on('itemClicked',function (e, args, status)
{
 //your actions  
});


$rootScope.$broadcast('$newItemsClicked');
$rootScope.$on('$newItemsClicked', function() {
 //your actions
});

4. Using Watch Concept.


Third method is using watch concept .Watch is a powerful feature of angular js. “$watch” concept in Angular is to observe the changes on the data of the scope from the controller.
Using Watch Concept

Related Posts

1. Angular flash message using directive

2. Angular routing

3. Rating Stars using angular js Directive concept

4. Communication between factory file and controller in Angular js