David Gustavsson David Gustavsson - 1 month ago 6
Javascript Question

How do i pass data through an ES6 "class" function in angular

Note that I'm kinda green in this area, so bare with me, please.

I'm trying to create a controller in angular as an ES6 class. This works as expected ( able to print the string returned through the message function). See below.

<div ng-controller="ProfilingCtrl as profileData">
{{profileData.message()}}
</div>


But what I want to do now i to be able to use a function class in ng-repeat, like below.

<div ng-controller="ProfilingCtrl as profileData">
<div ng-reapeat="x in profileData.getData()">
{{x[0]}}
</div>
</div>


getData() is a function returning an array of strings. Is this even possible? If not, how would one go about doing such an operation?

Thanks in advance.

Answer

Big chance your issue is coming from ng-reapeat -> typo should be ng-repeat. Still helping you with your code:

It would be useful if you shared your controller code. But I'll make something up.

First, unless you are trying to display the first character of each string in your data array, remove the [0], as x represents the element resulting from iteration.

<div ng-controller="ProfilingCtrl as profileData">
    <div ng-repeat="x in profileData.getData()">
        {{x}}
    </div>
</div>

Further recommendation: bind your data to a variable, instead of a function. ES6 style (though I would still stick with functions for controllers)

class MyController {

  constructor(myDataService) {
    this.myDataService = myDataService;

    this.myData = []; // This is where the data will be
  }

  handleError(error) {
    // do something error
  }

  getData() {
    this.myDataService.getData() // this is some method that returns a promise
      .then(response => this.myData = response) // response from http in a promise
      .catch(error => this.handleError(error));
  }

  $onInit() {  // angular will take care of starting this off
    this.getData();
  }

}

Note the $onInit is called by Angular when the component is ready. Read about lifecycle hooks: https://toddmotto.com/angular-1-5-lifecycle-hooks

The lifecycle hook is outside of scope of your question, but still nice to get into.

Note that the comment made earlier about "bind it to $scope" is not recommended. ControllerAs as you are doing is better, could later be put elsewhere though.