0

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');
    });     

}]);
halfer
  • 19,824
  • 17
  • 99
  • 186
davidlee
  • 5,611
  • 17
  • 56
  • 82

1 Answers1

0

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');
      });

  }
]);
Community
  • 1
  • 1
Claies
  • 22,124
  • 4
  • 53
  • 77
  • You can also bind the anon function of your success handler. May be useful if it isn't hard coded and for some strange reason your using callbacks and not returning the promise from a service. `.success(function (d) { //this will now be correct }.bind(this))` Obviously the value you bind will depend on context. – ste2425 Oct 23 '15 at 07:33