如何在对该范围外声明的变量的ng-repeat中使用ng-show?

Mer*_*lin 3 javascript jquery angularjs

我从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>
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助

Aru*_*hny 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>
Run Code Online (Sandbox Code Playgroud)

然后

app.controller('CommentController', function ($scope) {
    $scope.state = {}
    $scope.answers = [1, 2, 3]
})
Run Code Online (Sandbox Code Playgroud)

演示:小提琴


或访问ng-repeat transclude中的父范围 $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>
Run Code Online (Sandbox Code Playgroud)

演示:小提琴