Mike Makuch
Mike Makuch

Reputation: 1838

How to load data in a (1.5) angular component?

I'm able to get a basic component working, but trying to load some data via $http (users.get()) which returns a promise (the data does show up in console.log(this.data). But the data is not making it to the component template. Why?

.component('mrcUserInfo', {
bindings: {
    email: '<',
    first_name: '<',
    last_name: '<'
},
templateUrl: 'components/userInfo.html',
controller: function(users) {
    var scope = {};
    scope.thisId = 1;
    this.miketest = 'this is miketest';

    users.get(scope) // basically does a $http()...
    .then(function(data) {
        this.data = data.data;
        this.email = data.email;
        this.miketest = 'this is mike 2';

        console.log('user?');
        console.log(this.data);
    });
}

And my template has this

this is userInfo.html:
{{ $ctrl.miketest }}

The template displays 'this is miketest' but it does NOT display 'this is mike 2'

Any clues appreciated. Thanks. Mike

Upvotes: 1

Views: 555

Answers (1)

Igor Pantović
Igor Pantović

Reputation: 9246

Be careful when using this, especially in asynchronous code. In your specific case, this will be window object in your callback, so you're actually setting miketest variable on window rather than controller.

You can either do:

var ctrl = this;
users.get(scope) // basically does a $http()...
  .then(function(data) {
    ctrl.data = data.data;
    ctrl.email = data.email;
    ctrl.miketest = 'this is mike 2';

    console.log('user?');
    console.log(ctrl.data);
  });

Or explicitly bind this:

users.get(scope) // basically does a $http()...
  .then(function(data) {
    this.data = data.data;
    this.email = data.email;
    this.miketest = 'this is mike 2';

    console.log('user?');
    console.log(this.data);
  }.bind(this));

Additionally, if you're using something like BabelJS, and are able to use modern JavaScript features, you can use double arrow functions to bind this to lexical scope:

users.get(scope) // basically does a $http()...
  .then((data) => {
    this.data = data.data;
    this.email = data.email;
    this.miketest = 'this is mike 2';

    console.log('user?');
    console.log(this.data);
  });

Upvotes: 1

Related Questions