我有一个ng-repeat,它附有一个ng-if,带有一个子元素,我正在用ng-click更改。代码如下所示:
<div ng-repeat="object in objects" ng-if="show">
<div ng-click="show = !show">Show</div>
</div>
假设我有2个 objects
,它会加载两个重复的div,并且会有两个'show'元素。当我点击show时,它只会从页面中删除一个重复的元素。我需要它来删除这两个。想法?
答案 0 :(得分:1)
如果你想要隐藏所有内容,我会将所有内容包装在外部div中并放置&#34; ng-if&#34;那里。
<div ng-if="show">
<div ng-repeat="object in object">
<div ng-click="show = !show">Show</div>
</div>
</div>
但我建议将任何修改数据的逻辑放在TS文件而不是html视图中。
答案 1 :(得分:1)
你的模板几乎是正确的,唯一值得一提的是:
ngIf
内创建的范围继承自其父范围 使用原型继承。
prototypal inheritance的主要警告是在子范围上设置原始值会影响父范围上的值。有多种方法可以避免这种情况,请参阅下面的代码片段:
angular.module('app', [])
.controller('mainController', function mainController($scope) {
var ctrl = this;
$scope.show = true;
$scope.showList = {value: true};
$scope.objects = [{}, {}, {}];
$scope.toggleShowVar = function(){
$scope.show = !$scope.show;
};
ctrl.show = true;
});
&#13;
<!-- JS -->
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<body ng-app="app">
<div class="container" ng-controller="mainController as $mainCtrl">
<p>This will not work due to scope prototypal inheritance:</p>
<div ng-if="show">
<div ng-repeat="object in objects">
<div ng-click="show = !show">Show {{show}}</div>
</div>
</div>
<p>Using "controller as" will help us:</p>
<div>
<div ng-repeat="object in objects" ng-if="$mainCtrl.show">
<div ng-click="$mainCtrl.show = !$mainCtrl.show">Show {{$mainCtrl.show}}</div>
</div>
</div>
<p>Or simply using "dot in the model":</p>
<div>
<div ng-repeat="object in objects" ng-if="showList.value">
<div ng-click="showList.value = !showList.value">Show {{showList.value}}</div>
</div>
</div>
<p>Or using controller method for toggle:</p>
<div>
<div ng-repeat="object in objects" ng-if="show">
<div ng-click="toggleShowVar()">Show {{show}}</div>
</div>
</div>
<p>Or using $parent to change it in the controller's scope:</p>
<div>
<div ng-repeat="object in objects" ng-if="$parent.show">
<div ng-click="$parent.$parent.show = !$parent.$parent.show ">Show {{$parent.show}}</div>
</div>
</div>
</div>
</body>
&#13;