Friday 27 November 2015

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

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

ng-repeat



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

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


output



 one
 two
 three


ng-repeat-start and ng-repeat-end



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

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

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


Output



 start one
 one
 end one

 start two
 two
 end two

 start three
 three
 end three


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

Related Posts

1. Angular select all/de select all checkbox.

2. How to check lowercase in indexOf of an Array

3. Covert string to camel case using javascript

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


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

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



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


For applying filter you may try below code



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


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



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


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

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

Related Posts

1. Angular js client side pagination like google.

2. Angular Loader using font awesome icons

3. Angular js add class to active element


Tuesday 17 November 2015

Angular directive for scroll top.

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

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


 <scroll-up></scroll-up>

Directive


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

Related Posts

1. Angular js client side pagination like google.

2. Angular Loader using font awesome icons

3. Angular js add class to active element


Monday 16 November 2015

Jquery select all/de select all checkbox

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

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

Create a dynamic checkbox


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

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

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

_html += '</div>'

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

Select All/De Select All features



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


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


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

});

Related Posts

1. Angular select all/de select all checkbox.

2. How to check lowercase in indexOf of an Array

3. Covert string to camel case using javascript

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


Check Array.indexOf() with case insensitive.

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


var _name = "prasho";

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

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

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


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

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

Related Posts

1. Angular js client side pagination like google.

2. Angular Loader using font awesome icons

3. Angular js add class to active element


Sunday 25 October 2015

Angular select all/de select all checkbox

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

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

HTML



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

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

JSON


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

Select all deselect all angular code



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


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



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

Another Approach

Comparatively better approach suggested by TIM in the comment section.

HTML


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


JS



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

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

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


Related Posts

1. Angular js client side pagination like google.

2. Angular Loader using font awesome icons

3. Angular js add class to active element


Saturday 27 June 2015

Dynamically load css and javascript

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

Load javascript files using jquery


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

Load Jquery if it is not loaded


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

Load CSS using jquery


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

Load css if not loaded already


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

Related Posts

1. Covert string to camel case using javascript.

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

3. Angular js add class to active element


Sunday 26 April 2015

Angular js basic search and filter data with example

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

View

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

Your filter text box

 

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

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

JSON

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

Fiddle

Working Demo

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

Example of those have age 21

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

Example of those have age 41

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

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

Fiddle

Working Demo

Related Posts

1. Date filtering and formatting in Angular js.

2. Communicate with controllers in angular js

3. Rating Stars using angular js Directive concept

4. Angular routing

5. Loop concept in angular js



Thursday 23 April 2015

Get url parameter using angular js

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

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

For example


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

Even you can try ,


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

//you can write your own logic 

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

 

Check query parameter is existing


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

Related Posts

1. Angular js client side pagination like google.

2. Angular Loader using font awesome icons

3. Angular js add class to active element


Sunday 19 April 2015

Covert string to camel case using javascript

It is very easy to do using css


.className 
{
  text-transform:capitalize;
}

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


var myLabel = "sample text example"

var split = myLabel.split(' ');

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

myLabel= split.join(' ');

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


Related Posts

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

2. Save Google map as binary image

3. Top 10 professional bloggers in India - 2014

4. Auto complete using html5

5. Dynamic height for side bar


Sunday 22 March 2015

Angular switch statement

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

Example 1



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

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

Related Posts

1. Angular js client side pagination like google.

2. Angular Loader using font awesome icons

3. Angular js add class to active element


Saturday 21 March 2015

File upload and sending data to backend using angular js

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


Html


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

Controller


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

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


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

Factory file



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

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

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

Your file is successfully uploaded

Upload a file and send data and file to backend


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


uploadfile : function( files,success, error )
{

 var fd = new FormData();

 var url = 'your web service url';

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

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

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

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



Related Posts

1. How to download file from backend to UI

2. Communicate with controllers in angular js

3. Rating Stars using angular js Directive concept

4. Angular routing

5. Loop concept in angular js

6. Filtering concept in angular js

7. Auto complete using html5


Friday 13 March 2015

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

Using very minimum code we can achieve this.

Sample json data

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

]


Jquery

 

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

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

 

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

Demo

Related Posts

1. Create responsive highchart

2. About CK-Editor

3. Dynamic height for side bar