Deepankar Bajpeyi Deepankar Bajpeyi - 5 months ago 11
AngularJS Question

Why is vm not binding to this?

function ExampleCtrl(HttpGet){
'ngInject';

const vm = this;
vm.title = 'test';


HttpGet.get().then(function(response){
console.log(vm.title); //logs 'test';
vm.response = response.data;
console.log(vm.response); //logs the response;

});

}

export default {
name : 'ExampleCrl',
fn : ExampleCtrl
};


My View:

{{ home.response }}


UI Router:

$stateProvider
.state('Home', {
url : '/home/:page',
controller : 'ExampleCtrl as home',
templateUrl: 'home.html',
title : 'Home'
});


HttpGet
Service:

function HttpGet($http) {
'ngInject';

const service = {};

service.get = function () {
return new Promise(function(resolve, reject) {
$http.get('http://localhost:8000/all').success((data) => {
resolve(data);
}).error((err, status) => {
reject(err, status);
});
});
};

return service;

}

export default {
name: 'HttpGet',
fn: HttpGet
};


Isn't the whole point of doing
vm=this
is that inside a function block
this
is still bound ?

Answer

Your problem is not binding this. It is working fine.

Your problem is that you leave angular's digest cycle, so your html view is not updating.

  service.get = function () {
    return new Promise(function(resolve, reject) {
      $http.get('http://localhost:8000/all').success((data) => {
        resolve(data);
      }).error((err, status) => {
        reject(err, status);
      });
    });
  };

Here you creating new promise and call it's resolve function. But it is native ES6 promise. When it's then handler called, it is already outside of angular digest cycle.

So you should call ditest manually using

      $http.get('http://localhost:8000/all').success((data) => {
        $scope.$apply(() => resolve(data)); 
      }).error((err, status) => {

But you can solve this even simpler because $http.get already returns a promise. Just do:

  service.get = function () {
    return $http.get('http://localhost:8000/all');
  };

And that's all. $http.get already call digest for you.

And if you ever really need to create a promise in your angular code, then please use angular's $q service instead of ES6 promises because it already takes digest cycle into account.

Comments