SSuhat SSuhat - 1 year ago 116
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',
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?


Answer Source

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) {
          var loading = scope.isLoading;
          scope.$watch('isLoading', function(a, b) {
            element.attr('disabled', a);
<script src=""></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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download