我有一个onClick angularjs函数做一些绑定并有一个for循环。我的问题是for循环在第一次单击时不起作用。但在第二个确定。我该怎么办呢? 在我的应用程序中,我有一组学生firstname = fname,lastname = lname和学费。我希望当我点击学生姓名时,该程序会显示学生姓名,以及他或她的学费清单。
HTML:
<li ng-repeat="x in stdNames" class="text-center">
<a ng-cloak ng-click="showStuInfo($index)" href="#stu-info">{{ x.fname + ' ' + x.lname}}</a>
</li>
//result box (in another page - loading by router )
<section class="stuInfoBox clear">
<div class="nameRow clear">
<p class="text-right pull-right">Name</p><p class="text-right pull-right stu-fullname" ng-bind="studentName"></p>
</div>
<div class="tuitionsRow clear">
<ul class="stuTuitionList">
</ul>
</div>
</section>
JavaScript(AngularJS控制器):
//Students array
$scope.stdNames = [
{ stuId: "s01", fname: 'Mina', lname: 'Ghorbani', tuitions:['Javascript Programming','AngularJs','JQuery','C# Programming']};
//onclick function
$scope.showStuInfo = function (index) {
$(".stuTuitionList li").remove();
$scope.studentName = $scope.stdNames[index].fname + " " + $scope.stdNames[index].lname;
var tuitionsLength = $scope.stdNames[index].tuitions.length;
for (var i = 0; i < tuitionsLength; i++) {
$(".stuTuitionList").append("<li>"+$scope.stdNames[index].tuitions[i]+"</li>");
}
}
答案 0 :(得分:1)
我已经用您的示例创建了一个示例应用。它在这里正常工作,这是第一次初始化点击。请查看以下内容。
var app = angular.module('sample', []);
app.controller('samplecontroller', function($scope) {
//Students array
$scope.stdNames = [{
stuId: "s01",
fname: 'Mina',
lname: 'Ghorbani',
tuitions: ['Javascript Programming', 'AngularJs', 'JQuery', 'C# Programming']
}];
//onclick function
$scope.showStuInfo = function(index) {
$(".stuTuitionList li").remove();
$scope.studentName = $scope.stdNames[index].fname + " " + $scope.stdNames[index].lname;
var tuitionsLength = $scope.stdNames[index].tuitions.length;
for (var i = 0; i < tuitionsLength; i++) {
$(".stuTuitionList").append("<li>" + $scope.stdNames[index].tuitions[i] + "</li>");
}
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="sample">
<div ng-controller="samplecontroller">
<li ng-repeat="x in stdNames" class="text-center">
<a ng-cloak ng-click="showStuInfo($index)" href="#stu-info">{{ x.fname + ' ' + x.lname}}</a>
</li>
//result box (in another page - loading by router )
<section class="stuInfoBox clear">
<div class="nameRow clear">
<p class="text-right pull-right">Name</p>
<p class="text-right pull-right stu-fullname" ng-bind="studentName"></p>
</div>
<div class="tuitionsRow clear">
<ul class="stuTuitionList">
</ul>
</div>
</section>
</div>
</body>
&#13;