Angularjs 将切换功能仅应用于 ng-repeat 内单击的按钮

Angularjs Apply toggle function to only the clicked button inside ng-repeat

本文关键字:ng-repeat 单击 按钮 应用于 功能 Angularjs      更新时间:2023-09-28

我创建这个小提琴专门是为了解决我的问题。我正在ng-repeat某个部分。我有一个切换功能要在里面实现。但是,当我单击按钮时,所有重复的项目都会触发功能。尽管在单击时使用相同的函数名称,但在不使用ng-repeat时,这工作正常。下面是代码。我想有类似this运算符的东西,我可以在这里使用。到目前为止我的代码(我为小提琴而不是原始代码创建了这个(,

.HTML

<div ng-app="app">
    <div ng-controller="CommentController">
        <div ng-repeat="list in lists">
            <button ng-click="showDiv()" class="review">{{lists[$index]}}</button>
            <div ng-show="hiddenDiv">This is the div to be toggled on clicking any of the above button. And they do so as they make use of <i>same function on click.</i>
            </div>
        </div>
    </div>
</div>  

控制器

var app = angular.module('app', []);
app.controller('CommentController', function ($scope) {
    $scope.hiddenDiv = true;
    $scope.showDiv = function () {
        $scope.hiddenDiv = !$scope.hiddenDiv;
    };
    $scope.lists = ["one", "two", "three", "four", "five"];
});

如果您需要根据单击的按钮折叠一个特定的重复,请尝试以下操作,

将按钮修改为

<button ng-click="hiddenDiv = !hiddenDiv" class="review">{{lists[$index]}}</button>

并从控制器中删除$scope.showDiv功能

演示小提琴


描述

如果你使用喜欢,

 <button ng-click="showDiv()" class="review">{{lists[$index]}}</button>

单击该按钮时将从控制器触发$scope.showDiv函数,并且在该函数中$scope.hiddenDiv属性将切换,并注意 $scope.hiddenDiv 将对整个控制器可见,这意味着它对所有控制器范围都是通用的,因此,如果您更改它一次,使用该属性的所有其他内容都将更改,

但如果使用

<button ng-click="hiddenDiv = !hiddenDiv" class="review">{{lists[$index]}}</button>

然后,每个重复都有一个 hiddenDiv 属性,因为ng-repeat正在创建一个子范围 (DOC(。 因此,对于一个特定的重复,有一个单独的hiddenDiv属性,并且它对其他人不可见,它仅对相关重复可见。


如果您使用

<button ng-click="myData.hiddenDiv = !myData.hiddenDiv" class="review">{{lists[$index]}}</button>

请注意,您使用myData.hiddenDiv而不是hiddenDiv ,在这种情况下hiddenDiv angular 将检查myData子作用域中对象的属性ng-repeat然后 angular 意识到子作用域中没有称为myData的东西,然后它将在父作用域中搜索它,并且那里存在已实现的属性,并且该属性对于所有重复都是通用的,例如使用 showDiv() 函数。但是,如果您使用 hiddenDiv without 那么 Angular 将在ng-repeat子作用域中搜索它,并在意识到子作用域中不存在 hiddenDiv 后创建一个新的子作用域变量。

参见原型遗传。 这里有一个很好的描述。

也请检查说明

您还可以使用数组而不是单个变量,并在函数调用中传递索引,这样它就不会在一个操作中切换所有内容。

<div ng-app="app">
<div ng-controller="CommentController">
    <div ng-repeat="list in lists">
        <button ng-click="showDiv($index)" class="review">{{lists[$index]}}</button>
        <div ng-show="!hiddenDiv[$index]">This is the div to be toggled on clicking any of the above button. And they do so as they make use of <i>same function on click.</i>
        <input type="text" ng-model="textModel[$index]"/>{{textModel[$index]}}
        </div>
    </div>
</div>

控制器

var app = angular.module('app', []);
app.controller('CommentController', function ($scope) {
$scope.hiddenDiv=[];
$scope.textModel=[];
$scope.showDiv = function (index) {
    $scope.hiddenDiv[index] = !$scope.hiddenDiv[index];
    $scope.textModel[index]=null;
};
$scope.lists = ["one", "two", "three", "four", "five"];
});

http://jsfiddle.net/paje007/85vp9zme/6/

这样,如果您想在函数中执行任何操作,您也可以这样做,就像在小提琴中一样。在这里,我正在清除隐藏的文本输入。