如何在AngularJS中实现以下用例:如果前一个兄弟具有某种特定状态(例如$ scope上的字段)集,我需要一堆段落,每个段都必须可见。
<p ng-controller="genericCtrl as c1">
<button ng-click="someExpression = true">Show next</button>
</p>
<p ng-if="c1.someExpression" ng-controller="genericCtrl as c2">
<button ng-click="c2.someExpression = true">Show next</button>
</p>
<p ng-if="c2.someExpression" ng-controller="genericCtrl as c3">
... and so and so
</p>
上面的代码只是概念,因为你不能引用兄弟控制器。最好的是,如果我可以避免引用任何控制器并使用某种兄弟的东西。
答案 0 :(得分:1)
您的控制器仅适用于此段落,因此您的后续段落将无效,因为它们超出了此控制器的范围
<div ng-controller="genericCtrl as c1">
<p >
<button ng-click="someExpression = true">Show next</button>
</p>
<p ng-if="c1.someExpression" ng-controller="genericCtrl as c2">
<button ng-click="c2.someExpression = true">Show next</button>
</p>
<p ng-if="c2.someExpression" ng-controller="genericCtrl as c3">
... and so and so
</p>
</div>
因此,您需要一个顶级父级,并将其他控制器嵌套在其中
如果你只是想看看如何级联可见段落,这是一个示例性方法http://plnkr.co/edit/SdGZBR5khsVD9zojhQYS?p=preview
答案 1 :(得分:0)
看到你正在使用段落,你应该切换到div,这样你可以嵌套,你可以嵌套像这样的项目。 http://plnkr.co/edit/kUjrzlv2PmtyxgcZfFi0?p=preview
<div ng-controller="MainCtrl"> Test - Main
<button ng-click="c1 = true">Show Next 1</button>
<div ng-show="c1 == true" ng-controller="secondCtrl">
<button ng-click="c2 = true">Show Next 2</button>
<div ng-show="c2 == true" ng-controller="thirdCtrl">
<button ng-click="c3 = true">Show Next 3</button>
<div ng-show="c3 == true" ng-controller="fourthCtrl">
<button ng-click="c4 = true">Show Next 4</button>
</div>
</div>
</div>
</div>
这样,您可以创建子范围并且应该可以正常工作
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.c1 = false;
});
app.controller('secondCtrl', function($scope) {
$scope.c2 = false;
});
app.controller('thirdCtrl', function($scope) {
$scope.c3 = false;
});
app.controller('fourthCtrl', function($scope) {
$scope.c4 = false;
});
我相信这正是你要找的东西