AngularJS Components - How do I pass in a back end variable?

327 views Asked by At

I'm trying to component-ise my codebase and have come up stuck on this problem.

When using $scopes and Controllers I would pass a server token to my rest call method with ng-init. Trying to do the same with a Component is not working.

javascript

angular
.module('myApp', [])

.controller('mainCtrl', function() {
  var self = this;

  self.options = function() {
    var o = {}
    o.token = self.serverToken
    return o;
  }

  self.restData = {
    url: 'http://rest.url',
    options: self.options()
  }
})

.component('myComponent', {
  bindings: {
    restData: '<'
  },
  template: '<p>template, calls child components</p>',
  controller: function(restService) {

    this.callRestService = function() {
      restService.get(this.restData.url, this.restData.options) 
    }

    console.log(this.restData.url) // http://rest.url
    console.log(this.restData.options) // {token: undefined}
  }
})

html

<html ng-app="myApp">
  <!-- head -->

  <body ng-controller="mainCtrl as m" ng-init="m.serverToken='12345'">
    <my-component rest-data="m.restData"></my-component>
  </body>

</html>

How do I pass the value to the component?

1

There are 1 answers

1
mcgraphix On BEST ANSWER

The issue is that the ng-init is executed after the controller is instantiated. However you are creating your restData object during the construction of your controller at which time the serverToken is undefined.

You could build your restData object after ng-init is called with something like this:

.controller('mainCtrl', function() {
  var self = this;
  self.restData = {};

  self.init = function(token) {
    self.serverToken=token;
    self.restData = {
      url: 'http://rest.url',
      options: {token:token}
    };
  };
})

Your component can then do something when that restData changes. For example:

.component('myComponent', {
  bindings: {
    restData: '<'
  },
  template: '<p>template, calls child components</p>',
  controller: function(restService) {

    this.callRestService = function() {
       restService.get(this.restData.url, this.restData.options) 
    }

    this.$onChanges = function(changes) {

      console.log(this.restData) // http://rest.url
      console.log(this.restData.options) // {token: 12345}

      this.callRestService();
    }
  }
});

The HTML would change to call your init method:

<body ng-controller="mainCtrl as m" ng-init="m.init(12345)">
    <my-component rest-data="m.restData"></my-component>
   </body>