David Gustavsson David Gustavsson - 1 year ago 47
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">

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()">

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 Source

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()">

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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download