代码之家  ›  专栏  ›  技术社区  ›  Rahul Shivsharan

“this”关键字不适用于Angular控制器中的$http“success”方法

  •  0
  • Rahul Shivsharan  · 技术社区  · 11 年前

    我想从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”?

    2 回复  |  直到 11 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    有一个 question on the matter of this vs $scope .

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

    您可以使用 this 对于您希望远离 $范围 。但我宁愿保持一致,而不是混合 $范围 所以我通常会坚持 $范围 .

        2
  •  0
  •   Gustav    11 年前

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

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