0

當前我正在嘗試使用JSON獲取一些數據,並使用ng-repeat在我的網站上構建它。僅在所選的ng-repeat元素上調用函數

問題是,在ng-click上,在任何新創建的元素上,函數也會調用每個元素。我也嘗試使用這個運算符,但它似乎不適用於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> 

正如您可能會注意到,無論您何時單擊任何按鈕,該函數都會爲每個元素運行。我需要幫助以瞭解如何在此函數中傳遞任何標識符,以便僅在所單擊的元素上調用該函數。

+1

將'alphabet'作爲參數傳遞給'addDiv'函數。在函數中,您可以根據值來評估是否執行某些操作。 –

+0

請添加您的工作代碼的plunkr或jsfiddle! –

+0

將aplhabet作爲參數添加到ng-click =「addDiv(aplhabet」)中 –

回答

1

你需要一個對象數組來實現這一點。只需使用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爲true

演示

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>

0

你需要傳遞$index

<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 track by $index"> 
      <button style="width:50px; margin: 5px" ng-click="addDiv($index)"> 
       <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 (index) { 
       //do your stuff here 
      } 
     } 
    </script> 
</body> 
</html>