我想从ajax调用加载一个学院列表,并在UI中显示。
我在这个例子中使用的是AngularJS框架。
以下代码适用于College.html
<div class="page-header" ng-controller="CollegeController as collegeCntrl">
<div class="page-header">
<h3>Add/Manage Colleges</h3>
</div>
<ng-view />
</div>
以下代码用于list.html,
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>College-ID</th>
<th>College-Name</th>
<th>Edit College</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="college in collegeCntrl.collegeList | orderBy : 'collegeName'">
<td>{{college.collegeId}}</td>
<td>{{college.collegeName}}</td>
<td>
<a href="#/college/edit" class="btn btn-primary" ng-click="collegeCntrl.editCollege(college)">Edit</a>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="4">
<a href="#/college/addPage" class="btn btn-primary active">Add College</a>
</td>
</tr>
</tfoot>
</table>
以下代码来自college.js,
angular.module("CollegeModule",[])
.constant("collegeListURL","../rest/ser/college/list/One")
.controller("CollegeController",function($location, $http, collegeListURL){
$location.url("/loadingImage");
$http.get(collegeListURL).success(function(data){
this.collegeList = data;
$location.url("/college/list");
});
this.editCollege = function(college){
this.selectedCollege = college;
}
}
在上面的代码中,请查看
$http.get(collegeListURL).success(function(data){
this.collegeList = data;
$location.url("/college/list");
});
“this”关键字不适用于成功方法,
所以我用下面的代码块替换了上面的代码
(function(collegeCntrl){
$http.get(collegeListURL).success(function(data){
collegeCntrl.collegeList = data;
$location.url("/college/list");
});
})(this);
它奏效了。
所以我的问题是,对我有用的代码在AngularJS控制器中是一个很好的实践,
或者有其他方式来称呼“this”?