user1506145
user1506145

Reputation: 5286

Directive to disable and show load sign on a button during http-request

Consider this runnable example http://plnkr.co/edit/a88cOYDVORDHQV3b5NGJ?p=preview

angular.module('app', ['ngRoute'])
.controller('myctrl',['$scope', '$timeout', function($scope, $timeout){
  $scope.myjson = [{title:'one'},{title:'two'},{title:'three'}];

  $scope.remove = function(idx){
    $scope.loading = true;
    $timeout(function(){ 
      $scope.myjson.splice(idx,1);
      $scope.loading = false
    }, 700)

  }
}])
.filter('unsafe', function($sce) {
    return function(val) {
        return $sce.trustAsHtml(val);
    };
})
</script>

<div ng-controller="myctrl">
  <div ng-repeat="j in myjson">
  <a class="btn btn-default" 
  ng-bind-html=" loading? 
  ( '<i class=\'fa fa-refresh fa-spin\'></i>' | unsafe) : 
  ('Save' | unsafe)" 
  ng-disabled="loading"
  ng-click="remove($index)">Remove</a> 
  <b>{{j.title}}</b>
  </div>
</div>

The timeout is to simulate a http-request removing entities. This works if there is just one button (for example login or register). The problem is that each of the entities need to have their individual loading variable, and I don't know how to do it. I just want the button clicked on to show the loading symbol. For many buttons like this I think I need a directive...

Upvotes: 0

Views: 319

Answers (1)

Yaron Schwimmer
Yaron Schwimmer

Reputation: 5357

This is why they invented Angular directives. You can create a directive with an isolated scope, and apply it to each of your buttons.

angular.module('app', ['ngRoute'])
.controller('myctrl',['$scope', '$timeout', function($scope, $timeout){
  $scope.myjson = [{title:'one'},{title:'two'},{title:'three'}];
}]).directive('loader',function() {
  return {
    restrict: 'A',
    scope: true,
    controller: ['$scope', '$timeout', function($scope, $timeout) {
      $scope.remove = function(idx){
        $scope.loading = true;
        $timeout(function(){ 
          $scope.myjson.splice(idx,1); 
          $scope.loading = false
        }, 700)

      }
    }]
  };
})

I've changed your plunkr to demonstrate.

Upvotes: 1

Related Questions