angularjsangularjs-rootscope

Disable button in one controller from another


Consider I have two controllers Ctrl1 and Ctrl2. On clicking a button in Ctrl1, the button in Ctrl2 should be disabled.

Any sample code for this??


Solution

  • Without $rootScope :

    var myApp = angular.module('myApp', []);
    
    function Controller2($scope, ButtonService) {
      $scope.object = ButtonService.getValue();
    };
    
    function Controller1($scope, ButtonService) {
    
      $scope.changeValue = function() {
        ButtonService.getValue(true);
      };
    
    };
    
    myApp.factory('ButtonService', function() {
      var obj = {}
      return {
    
        getValue: function(update) {
          var defaultValue = false;
    
          if (typeof(update) === 'undefined') {
            obj.val = defaultValue;
          } else {
            obj.val = update;
          }
          return obj;
        }
      }
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <body ng-app="myApp">
    
      <div ng-controller="Controller1">
        <button ng-click="changeValue()">Click to change Value</button>
      </div>
    
      <div ng-controller="Controller2">
        <button ng-disabled="object.val">{{!object.val ? 'Enabled Button' : 'Disabled Button'}}</button>
      </div>
    
    </body>

    With $rootScope :

    var myApp = angular.module('myApp', []);
    
    myApp.service('myService', function($rootScope) {
      var self = this,
        disabledButton = false;
    
      this.setDisabledButton = function() {
        // Change here if you want to toggle on click
        if (!disabledButton) {
          disabledButton = true;
          $rootScope.$broadcast("btnDisabled", disabledButton);
        } else {
          return;
        }
    
      }
    
      this.getDisabledButton = function() {
        return disabledButton;
      }
    });
    
    myApp.controller('Ctrl1', function($scope, myService) {
      $scope.disabledControllerButton = function() {
        myService.setDisabledButton();
      }
    });
    
    myApp.controller('Ctrl2', function($scope, myService) {
      $scope.$on('btnDisabled', function(event, param) {
        $scope.Ctrl1ButtonClicked = param;
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    
    <body ng-app="myApp">
      <div ng-controller="Ctrl1">
        <button ng-click="disabledControllerButton()">
        Click to Change
      </button>
      </div>
    
      <div class="container" id="main" ng-controller="Ctrl2">
        <button ng-disabled="Ctrl1ButtonClicked">
        {{Ctrl1ButtonClicked ? 'Disabled ' : 'Enabled '}} Button
      </button>
      </div>
    </body>

    Kindly check this snippet. It might help you out.