gpt4 book ai didi

javascript - Angular 确保在打开另一个开关时关闭开关

转载 作者:行者123 更新时间:2023-11-28 19:20:55 25 4
gpt4 key购买 nike

有两个不同的 div,可以在 Angualar 应用程序中切换打开和关闭,但要确保如果一个打开,另一个就会关闭。看起来这在 NG 中应该足够简单,但对于 Angular 来说仍然是新鲜事。有人指点一下吗?

在这里制作了一个 fiddle 示例: JS Fiddle

这是示例:

 <body ng-app="simpleToggle">
<div ng-controller="AppCtrl">
<button ng-click="toggleCustom1()">Custom</button>
<span ng-hide="custom1">
<h2>Custom 1 is showing but Custom 2 should not be if it was already opened</h2>
</span>
<span ng-show="custom1"></span>
</div>

<div ng-controller="App2Ctrl">
<button ng-click="toggleCustom2()">Custom2</button>
<span ng-hide="custom2">
<h2>Custom 2 is showing but Custom 1 should not be if it was already opened.</h2>
</span>
<span ng-show="custom2"></span>
</div>
</body>

angular.module('simpleToggle', [])
.controller('AppCtrl',['$scope', function($scope){
$scope.custom1 = true;
$scope.toggleCustom1 = function() {
$scope.custom1 = $scope.custom1 === false ? true: false;
};
}])
.controller('App2Ctrl',['$scope', function($scope){
$scope.custom2 = true;
$scope.toggleCustom2 = function() {
$scope.custom2 = $scope.custom2 === false ? true: false;
};
}]);

最佳答案

在这里,您正在处理作用域层次结构,您将希望使用其中一种机制来在 Controller 之间进行协调。一些选项是:

  1. 使用$rootScope
  2. 使用消息

我已更新您的示例以在此处使用 $rootScope http://jsfiddle.net/4q7hrpc5/3/

首先,创建一些东西来初始化$rootScope。我创建了一个外部 Controller 并将其他两个 Controller 包装在该 Controller 中。以下是更新后的 HTML:

<body ng-app="simpleToggle">
<div ng-controller="OuterCtrl">
<div ng-controller="AppCtrl">
<button ng-click="toggleCustom1()">Custom</button>
<span ng-hide="!custom1">
<h2>Custom 1 is showing but Custom 2 should not be if it was already opened</h2>
</span>
</div>

<div ng-controller="App2Ctrl">
<button ng-click="toggleCustom2()">Custom2</button>
<span ng-hide="!custom2">
<h2>Custom 2 is showing but Custom 1 should not be if it was already opened.</h2>
</span>
</div>
</div>
</body>

这是 Controller 的代码:

angular.module('simpleToggle', [])
.controller('OuterCtrl', ['$rootScope', function($rootScope) {
$rootScope.custom1 = false;
$rootScope.custom2 = false;
}])
.controller('AppCtrl',['$rootScope', '$scope', function($rootScope, $scope){
$scope.toggleCustom1 = function() {
$rootScope.custom1 = !$rootScope.custom1;
$rootScope.custom2 = false;
};
}])
.controller('App2Ctrl',['$rootScope', '$scope', function($rootScope, $scope){
$scope.toggleCustom2 = function() {
$rootScope.custom2 = !$rootScope.custom2;
$rootScope.custom1 = false;
};
}]);

现在,这种特定技术仅适用于少数必须协调的事情。如果您有大量需要协调的事情,那么消息或服务可能会更好。另一种选择是将它们全部放入同一个 Controller 中。

关于javascript - Angular 确保在打开另一个开关时关闭开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28933879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com