javascriptangularjsjavascriptmvc

the 'this' keyword don't work for $http 'success' method in Controller of Angular


I want to load a list of colleges from an ajax call and display in UI. I am using AngularJS framework for this example.

the bellow code if for College.html

<div class="page-header" ng-controller="CollegeController as collegeCntrl">
  <div class="page-header">
     <h3>Add/Manage Colleges</h3>
  </div>
<ng-view />     
</div>

The below code is for 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>

The below code is from 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;
    }
}

in the above code please look at the code for

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

the 'this' keyword don't work for the success method, so i replaced the above code with the below block of code

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

And it worked.

So my question is the code which worked for me can be a good practice in AngularJS controller, or there is a other way to refer 'this' ?


Solution

  • You should inject $scope in your controller and set $scope.collegeList = data;

    Then in you html instead of college in collegeCntrl.collegeList, you just remove collegeCntrl.: college in collegeList