SSuhat SSuhat - 2 months ago 8
AngularJS Question

Angular directive set scope watch to disabled button

I want to make disabled a button based on scope changes.

Here is my current directive code:

function disabledButton(){
return {
restrict: 'EA',
priority:1001,
scope:{
isLoading: '=loading'
},
link:(scope, element, attrs, isLoading)=>{
scope.$watch('isLoading', () => {
element.attr('disabled', true);
});
}
}
}


my html:

<button type="submit" class="pull-right" disabled-button>Update</button>


My Controller just a simple:

$scope.loading = true;


But it's not working. The button is not disabled.

Any solution?

JSfiddle
https://jsfiddle.net/ssuhat/gp6tq0Lt/7/

Answer

link and compile do not work together.

In the directive definition object, if you only define link, that's like shorthand for having an empty compile function with an empty preLink function with your code in the postLink function. As soon as you define compile, link is ignored by angular, because compile should return the linking functions.

If you only return one function from compile, then it'll be executed post link.

angular.module('app', [])
  .controller('myctrl', function($scope, $timeout) {
    $scope.loading = true;
    $scope.change = function() {
      $scope.loading = !$scope.loading;
    }
  })
  .directive('disabledButton', function() {
    return {
      restrict: 'AE',
      scope: {
        isLoading: '='
      },
      compile: function() {
        return function(scope, element, attrs) {
          console.log(element);
          var loading = scope.isLoading;
          scope.$watch('isLoading', function(a, b) {
            element.attr('disabled', a);
          });
        }
      }
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="myctrl">
    <button ng-click="change()">dsa</button>
    <div class="row">
      <button is-loading="loading" disabled-button>Update</button>
    </div>
  </div>
</div>

Comments