从一个控制器中禁用另一个控制器中的按钮



考虑我有两个控制器Ctrl1和Ctrl2。单击 Ctrl1 中的按钮时,应禁用 Ctrl2 中的按钮。

任何示例代码??

不带$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>

$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>

请检查此片段。它可能会帮助你。

您有 3 个选项:

  1. 角度事件:使用相关控制器(Ctrl1(的$broadcast$emit通知兄弟控制器(Ctrl2(,在接收控制器使用$on监听事件见角度事件。
  2. 第二个选项:对两个控制器使用父作用域,并在其上保存按钮的状态 - 假设您有 CtrlP 具有您在 CtrlP$scope上设置的父级,该属性$scope.isButton2Disabled为 false。 然后在子控制器 Ctrl1 上单击处理程序上添加以下行$scope.$parent.isButton2Disabled = true;在 Ctrl2 的视图中添加ng-disabled="isButton2Disabled"见小提琴
  3. 最后一个和 IMO 最糟糕的方式,只需在初始化应用程序时使用$rootScope并设置$rootScope.isButton2Disabled = false;,然后在单击 Ctrl1 中的按钮时,在单击处理程序中添加以下代码:$rootScope.isButton2Disabled = true;您现在需要的只是在 #2 上执行相同的操作,将ng-disabled="isButton2Disabled"添加到要禁用的按钮。

进一步阅读:使用 angular 共享数据

您可以通过以下实现来执行此操作。

1.Module.service() 
2.Module.factory() 
3.Module.provider()
4.Module.value()
5.using $parent in HTML code
6.using $parent in child controller
7.using controller inheritance
8.Holding the shared data in the root scope
9.Using $emit,$broadcast

最新更新