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


5 comments :

  1. thanks!!!!!!!!

    ReplyDelete
  2. What if I want one state to show by default?

    ReplyDelete
    Replies
    1. You can write this $scope.state = "LOADING" ; on your init function or anywhere in your controller

      Delete
  3. I generally like the blog and I really respect your content.
    Phrases are my favorite.
    I will bookmark your site and continue to explore new data.
    spotif premium pc
    youtube video download y2mate
    pro evolution soccer 2017
    iboysoft data recovery
    need for speed

    ReplyDelete