'this'关键字不适用于 Angular 控制器中的$http"成功"方法



我想从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"不适用于success方法,所以我用下面的代码块替换了上面的代码

(function(collegeCntrl){
    $http.get(collegeListURL).success(function(data){
        collegeCntrl.collegeList = data;
        $location.url("/college/list");
    });
})(this);

它奏效了。

所以我的问题是,为我工作的代码可以在AngularJS控制器中成为一个很好的实践,或者还有其他方式来指代"这个"?

有一个关于this与$scope的问题。

$scope的常见用途是您想直接在HTML上访问的任何内容。

对于要远离$scope的方法或属性,可以使用this。但我宁愿保持一致,不混合this$scope,所以我通常坚持使用$scope

您应该在控制器中注入$scope并设置$scope.collegeList = data;

然后在html而不是college in collegeCntrl.collegeList中,只需删除collegeCntrl.:college in collegeList

最新更新