我相信这是一个非常简单的问题,我在论坛上找到了一些解决方案,但看起来我做的一切都是正确的,但仍然只得到最后的值。我写了这个简单的 example 。有人可以解释我,我的错误在哪里?
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$scope.name = 'Reinforcement';
$http.get('test.json')
.success(function (data) {
$scope.test = data;
});
$scope.getName = function () {
for (var i = 0; i < $scope.test.length; i++) {
$scope.parent = $scope.test[i].name
}
}
});
html
<div class="dropdown category" style="position:relative">
<a href="#" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> Category <span class="caret"></span></a>
<ul class="dropdown-menu">
<li ng-repeat="objName in test" ng-click="getName()">
<a href=""> {{objName.name}}</a>
</li>
</ul>
</div>
{{ parent }}
最佳答案
使用 ng-repeat
$index
获取名称。
不要循环你的模型,看看它更简单:
<p>Hello {{name}}!</p>
<div class="dropdown category" style="position:relative">
<a href="#" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> Category <span class="caret"></span></a>
<ul class="dropdown-menu">
<li ng-repeat="objName in test" ng-click="getName($index)">
<a href=""> {{objName.name}}</a>
</li>
</ul>
</div>
{{ selectedCategory }}
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$scope.name = 'Reinforcement';
$http.get('test.json')
.success(function (data) {
$scope.test = data;
});
$scope.getName = function (index) {
console.info($scope.test[index].name);
$scope.selectedCategory = $scope.test[index].name;
}
});
注意/建议:避免使用像 parent
这样的模型名称,因为您可能会与允许访问父范围的 $parent
混淆。
在第二种情况下,您必须使用 $parent.$index
获取父 $index (因为嵌套 ng-reapeat),但它是相同的技巧=数组模型上没有循环:
html:
<ul class="dropdown-menu">
<li class="dropdown" ng-repeat="entity in entitis" >
<a class="trigger right-caret">{{ entity }}</a>
<ul ng-if="entity | filter : 'Main'" class="dropdown-menu sub-menu">
<li ng-repeat="domain in ast" ng-click="getDomain($parent.$index, $index)">
<a href=""> {{domain.name}}</a>
</li>
</ul>
</li>
</ul>
</div>
{{ items }}
<br/>
<br/>
<p><b>parent index : {{astParentIndex}}</b></p>
<p><b>index : {{astIndex}}</b></p>
js
$scope.getDomain = function (parentIndex, index) {
$scope.astParentIndex = parentIndex;
$scope.astIndex = index;
$scope.items = $scope.ast[parentIndex].children;
}
关于javascript - Angular for 循环返回最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36460110/