目前我正在尝试使用JSON获取一些数据,并使用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>
您可能会注意到,无论何时单击任何按钮,该函数都会针对每个元素运行。我需要帮助来了解如何在此函数中传递任何标识符,以便仅在单击的元素上调用该函数。
答案 0 :(得分: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>
答案 1 :(得分: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>