如何在该范围外声明的变量上的ng-repeat内进行ng-show?

梅林

我从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>

谢谢你的帮助

阿伦·P·约翰尼(Arun P Johny)

这是因为ng-repeat创建了一个新的作用域,并且其中包含的已包含在内的元素位于一个单独的作用域中,因此您可以使用类似

<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]
})

演示:小提琴


或使用以下命令在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>

演示:小提琴

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章