javascript - 仅在选定的 ng-repeat 元素上调用函数

标签 javascript angularjs angularjs-ng-repeat angularjs-ng-click

目前,我正在尝试使用 JSON 获取一些数据,并使用 ng-repeat 在我的网站上构建它。

问题是,在 ng-click 上,在任何新创建的元素上,该函数也会在每个元素上调用。我也尝试过使用 this 运算符,但它似乎不适用于 angularjs。

我创建了一个与我的类似的虚拟问题。

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
    <div ng-controller="MyCtrl">
        <div ng-repeat="aplhabet in word">
            <button style="width:50px; margin: 5px"  ng-click="addDiv()">
                <b>{{aplhabet}}</b>
            </button>
            <section ng-show="newdiv">functionInvoked</section>
        </div>
    </div>

    <script>
        var myApp = angular.module('myApp',[]);
        function MyCtrl($scope){
            $scope.word = 'STRINGDEMO';    
            $scope.addDiv = function () {
                $scope.newdiv = true;
            }
        }
    </script>
</body>
</html>

您可能会注意到,每当您单击任何按钮时,该函数就会针对每个元素运行。我需要帮助来理解如何传递此函数中的任何标识符,以便仅在单击的元素上调用该函数。

最佳答案

您需要一个对象数组来实现此目的。只需使用 for 循环将其转换为对象数组即可。

for(key in $scope.word){
  $scope.wordArr.push({
      letter : $scope.word[key],
      newDiv : false
  })
}

使用新数组 ng-repeat 。打印信件使用 <b>{{aplhabet.letter}}</b>

<div ng-repeat="aplhabet in wordArr">
  <button style="width:50px; margin: 5px"  ng-click="addDiv(aplhabet)">
    <b>{{aplhabet.letter}}</b>
  </button>
  <section ng-show="aplhabet.newdiv">functionInvoked
  </section>
</div>

ng-click将整个对象作为参数传递并更改 newDiv为真

演示

var myApp = angular.module('myApp',[]);
function MyCtrl($scope){
$scope.word = 'STRINGDEMO';  
$scope.wordArr = [];

for(key in $scope.word){
  $scope.wordArr.push({
      letter : $scope.word[key],
      newDiv : false
  })
}
$scope.addDiv = function (aplhabet) {
   aplhabet.newdiv = true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div ng-repeat="aplhabet in wordArr">
<button style="width:50px; margin: 5px"  ng-click="addDiv(aplhabet)">
<b>{{aplhabet.letter}}</b>
</button>
<section ng-show="aplhabet.newdiv">functionInvoked
</section>
</div>
</div>

关于javascript - 仅在选定的 ng-repeat 元素上调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44570028/

相关文章:

javascript - 在 Laravel Form Open 中使用 Jquery Confirm?

javascript - 如何使用 AngularJS Controller 在 $http.get 中指定 MongoDB 键/值参数?

javascript - AngularJS 路由问题错误的 URL

javascript - 从 Angular 服务调用 Angular 路径以加载新 View 和 Controller

javascript - 将值保存到 AngularJS 中 ng-repeat 内复选框上的数组

javascript - 绑定(bind)在 ng-repeat 内的嵌套元素中不起作用

javascript - angularjs 嵌入和 ng-repeat : doing it right

javascript - 想要将日期选择器日历作为对话框打开

javascript - 尝试使用 Javascript 输出到文本框

javascript - Angularjs-UI Bootstrap : Accordion Open and close all