我从Angular.js开始,我遇到ng-show
的问题。
当我点击第一个块#first-block
时,第二个块#second-block
切换其ng-show / ng-hide。这很有效。
但是当我点击第三个块#third-block
时,我想要相同的行为。
这不起作用。
我尝试使用ng-click="show = true"
但没有成功。
<div ng-controller="CommentController">
<div id="first-block" ng-click="show = !show">
<!--first block-->
</div>
<div id="second-block" ng-show="show" >
<!--second block that toggle show/hide when I click on first block.-->
</div>
<div ng-repeat="answer in answers" >
<div id="third-block" ng-click="show = !show">
<!--third block. Nothing is happening when I click on this one.-->
</div>
</div>
</div>
感谢您的帮助
答案 0 :(得分:5)
这是因为ng-repeat创建了一个新范围,其中的transcluded元素位于一个单独的范围内,您可以使用像
这样的对象<div id="first-block" ng-click="state.show = !state.show">1</div>
<div id="second-block" ng-show="state.show">2</div>
<div ng-repeat="answer in answers" >
<div id="third-block" ng-click="state.show = !state.show">{{$index}}</div>
</div>
然后
app.controller('CommentController', function ($scope) {
$scope.state = {}
$scope.answers = [1, 2, 3]
})
演示:Fiddle
或使用$parent
<div id="first-block" ng-click="show = !show">1</div>
<div id="second-block" ng-show="show">2</div>
<div ng-repeat="answer in answers" >
<div id="third-block" ng-click="$parent.show = !$parent.show">{{$index}}</div>
</div>
演示:Fiddle
答案 1 :(得分:4)
ng-repeat
在每次迭代时创建一个新范围作为当前范围的子范围。
访问父作用域可以执行的操作是使用$parent
。例如:
<div id="first-block" ng-click="show = !show">
<!--first block-->
</div>
<div id="second-block" ng-show="show" >
<!--second block that toggle show/hide when I click on first block.-->
</div>
<div ng-repeat="answer in answers" >
<div id="third-block" ng-click="$parent.show = !$parent.show">
<!--third block. Nothing is appening when I click on this one.-->
</div>
</div>
查看AngularJS对understanding scopes
的解释