考虑我有两个控制器Ctrl1和Ctrl2。单击Ctrl1中的按钮时,应禁用Ctrl2中的按钮。
这个的任何示例代码??
答案 0 :(得分:1)
没有$ 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>
&#13;
使用$ 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;
});
});
&#13;
<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>
&#13;
请检查此代码段。它可能会帮助你。
答案 1 :(得分:1)
您有3个选项:
$broadcast
或$emit
(Ctrl1)通知兄弟控制器(Ctrl2),在reciveing控制器上使用$ on来监听事件,请参阅{{ 3}}。$scope
上设置的父项属性$scope.isButton2Disabled
为是假的。然后在点击处理程序上的子控制器Ctrl1上,在Ctrl2的视图上添加以下行$scope.$parent.isButton2Disabled = true;
,添加ng-disabled="isButton2Disabled"
请参阅Angular Events $rootScope
并在初始化应用时设置$rootScope.isButton2Disabled = false;
,然后在单击Ctrl1中的按钮时,在点击处理程序中添加以下代码: $rootScope.isButton2Disabled = true;
您现在需要的是在#2添加ng-disabled="isButton2Disabled"
上对要禁用的按钮执行相同操作。进一步阅读:Fiddle
答案 2 :(得分:1)
您可以通过以下实施来实现。
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