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


Thursday, 20 March 2014

Save highstock as binary image

Here I am going to explain how to save highstock chart as a binary image .

Highstock View

Here we are plotting Highstock .

 
 <div id="chart"></div>
 

For converting Highstock to binary image ,first we have to convert this to canvas .

View

 
 <canvas id="canvas" width="1000px" height="600px" 
           style="display:none;"></canvas>
 
 <img class="binaryimage">
 

Here first we have to find the svg

 
var svg = document.getElementById('chart').children[0].innerHTML;
 

Note : If zero is not working you can try with one .Here we are just trying to find the svg

Controller

 
var svg = document.getElementById('chart').children[0].innerHTML;
    
canvg(document.getElementById('canvas'),svg);
    
var img = canvas.toDataURL("image/png"); 

//img is data:image/png;base64
    
img = img.replace('data:image/png;base64,', '');
    
$('.binaryimage').attr('src', 'data:image/png;base64,'+img);

 

You can take this html of binary image and can save to db or you can save only the binary code.

You can include these also

 
<script type="text/javascript" 
  src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js">
</script> 

<script type="text/javascript" 
  src="http://canvg.googlecode.com/svn/trunk/StackBlur.js">
</script>

<script type="text/javascript" 
  src="http://canvg.googlecode.com/svn/trunk/canvg.js">
</script> 
 

Demo

Play in fiddle

Save highchart as binary image

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.

You can refer about highstock here highcharts.com/
And for highstock highcharts.com/highstock.

I am explaining here how to save angular highchart as a binary image.

View

 
<higchart id="highchartContainer" config="highchart" ></highchart> 
 

Angular code

 
$scope.highchart ={
 options : {
  chart : {
   type : 'bar'
  }
  },
  series :[{
  data : [ 20 ,40 ,50 ,60 ]
  }],
  title : {
  text : 'sample text'
  },
  loading : false 
 }
 

Save higchart as binary image .

 
  
<button ng-click="saveAsBinary();">Save </button>

<img id="binaryImage"/>
 

 
$scope.saveAsBinary = function( ){
 
 var svg = document.getElementById('highchartContainer')
                                     .children[0].innerHTML;
// svg = chart.getSVG();   
    
 var base_image = new Image();
    
 svg = "data:image/svg+xml,"+svg;
    
 base_image.src = svg;
    
 $('#binaryImage').attr('src', svg);

}
  

You can take this html or binary code and can save in DB directly.

If you are facing any issue with firfox you can try above method ( highstock to binary image) .Basically both are using same logic and no issues in firfox except you need support of some other plugins .

Demo

Play in fiddle

Related Posts

1. Create responsive highchart

2. Angular flash message using directive

3. Angular routing

4. Rating Stars using angular js Directive concept

5. Communicate with controllers in angular js


Saturday, 15 March 2014

Save Highchart as binary image.

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.

You can refer about highstock here highcharts.com/
And for highstock highcharts.com/highstock.

I am explaining here how to save angular highchart as a binary image.

View

 
<higchart id="highchartContainer" config="highchart" ></highchart> 
 

Angular code

 
$scope.highchart ={
 options : {
  chart : {
   type : 'bar'
  }
  },
  series :[{
  data : [ 20 ,40 ,50 ,60 ]
  }],
  title : {
  text : 'sample text'
  },
  loading : false 
 }
 

Save higchart as binary image .

 
  
<button ng-click="saveAsBinary();">Save </button>

<img id="binaryImage"/>
 

 
$scope.saveAsBinary = function( ){

 var svg = document.getElementById('highchartContainer')
                                       .children[0].innerHTML;
// svg = chart.getSVG();   
    
 var base_image = new Image();
    
 svg = "data:image/svg+xml,"+svg;
    
 base_image.src = svg;
    
 $('#binaryImage').attr('src', svg);

}
  

You can take this html or binary code and can save in DB directly.

If you are facing any issue with firfox you can try below method ( highstock to binary image) .Basically both are using same logic and no issues in firfox except you need to add some more plugins .

Demo

Play in fiddle

Save Highstock chart as binary image

Here I am going to explain how to save highstock chart as a binary image .

Highstock View

Here we are plotting Highstock .

 
 <div id="chart"></div>
 

For converting Highstock to binary image ,first we have to convert this to canvas .

View

 
 <canvas id="canvas" width="1000px" height="600px" 
           style="display:none;"></canvas>
 
 <img class="binaryimage">
 

Here first we have to find the svg

 
var svg = document.getElementById('chart').children[0].innerHTML;
 

Note : If zero is not working you can try with one .Here we are just trying to find the svg

Controller

 
var svg = document.getElementById('chart').children[0].innerHTML;
    
canvg(document.getElementById('canvas'),svg);
    
var img = canvas.toDataURL("image/png"); 

//img is data:image/png;base64
    
img = img.replace('data:image/png;base64,', '');
    
$('.binaryimage').attr('src', 'data:image/png;base64,'+img);

 

You can take this html of binary image and can save to db or you can save only the binary code.

Demo

Play in fiddle

You can include these also

 
<script type="text/javascript" 
  src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js">
</script> 

<script type="text/javascript" 
  src="http://canvg.googlecode.com/svn/trunk/StackBlur.js">
</script>

<script type="text/javascript" 
  src="http://canvg.googlecode.com/svn/trunk/canvg.js">
</script> 
 

Related Posts

1. Create responsive highchart

2. Angular flash message using directive

3. Angular routing

4. Rating Stars using angular js Directive concept

5. Communicate with controllers in angular js


Thursday, 13 March 2014

Flash message using directive in Angular js

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. I am going to explain how to display a flash message using directive concept in Angular js.

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

Directive

'restrict' option is used to

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

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

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

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

 
angular.module('yourmodule').directive('spFlash',
function() {
 return {
  restrict : 'A',
  replace : true,
  template : '<div class="flash row-fluid">'
 
 + '<div class="flash-inner span4 offset4 alert alert-success"
 
 data-ng-repeat="msg in successMsg">{{msg}}</div>'
 
 + '</div>',

 // If you are using twitter bootsrtap along with angular
 //then you can use this classes span4 ,offset4 ,alert etc 
 //or you can define your own css for better look an feel.
 
 link : function($rootScope, scope, element, attrs) {
  $rootScope.$watch('successMsg', function(val) {
   if (val.length) {
    update();
   }
  }, true);
   
 function update() {
  $('.flash')
   .fadeIn(500).delay(3000)
   .fadeOut(500, function() {
   $rootScope.successMsg.splice(0);
  });
 }
   }
  };
 }
);

 

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. That is controller can add a listener on an attribute of its scope.

Controller

Just copy the one line of code and display flash message anywhere in your application.


angular.module('sampleproject').controller( 'sampleController',
function ($rootScope, $scope ,$location )
{
 $scope.samplefunction = function(){
  //Flash message
  $rootScope.successMsg.push('success');
 };
});

CSS

You can write your own css for better look an feel.


.flash {
 position: absolute;
 top: auto;
 left: 0;
 width: 100%;
 display: none;
 }
.flash-inner {
  your styles ...
 }


Include this on header or where you need to show the message


<div data-sp-flash></div>

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. Save highchart as binary image