angularjsangularjs-ng-repeatng-controller

Display attribute of ngrepeat from ngcontroller alias


Without the ngcontroller alias, I can fetch the data. However, when with alias, I can't. What is my mistake here?

HTML tags:

<div style="padding: 10px" id="content_dv" ng-controller="displaytopic_ctrl as f">
     <div class="topic_dv" ng-repeat="t in f.topic">
        <p>{{ t.MEMBER_NAME }}</p>
     </div>
</div>

in app.js:

.controller('displaytopic_ctrl', ['$http', function($http) {

    $http({
        method: 'get',
        url: api_url + 'get_topic_list.php', 
        data: {
            type: 'all'
        }

    }).success(function(d){     
        if(d.t=='p'){
            this.topic = d.topic;
        }
    }).error(
    function(){
        console.log('Query error');
    });     

}]);

Solution

  • Due to the way JavaScript closures work, the this variable that you are using in your success callback is not the controller. The most commonly used mechanism to solve this is to create an alias for the controller which you can reference inside your callbacks.

    For Example:

    .controller('displaytopic_ctrl', ['$http',
      function($http) {
        var controller = this;
    
        $http({
          method: 'get',
          url: api_url + 'get_topic_list.php',
          data: {
            type: 'all'
          }
    
        }).success(function(d) {
          if (d.t == 'p') {
            controller.topic = d.topic;
          }
        }).error(
          function() {
            console.log('Query error');
          });
    
      }
    ]);