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

时间:2014-01-17 12:02:06

标签: 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>

感谢您的帮助

2 个答案:

答案 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

访问ng-repeat转录中的父作用域
<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

的解释