Killouis
Killouis

Reputation: 21

Access variable in Ember controller

how can I access a variable in Ember controller? I've tried those methods, but it doesn't work:

import ObjectController from '@ember/controller';
export default ObjectController.extend({

  currentPhase: 1,

  init: function () {
      var selfReference = this;
      this.set("currentPhase",1);
  },

  strings: {
      title: "Title",
      phase1: "Fase " + selfReference.get("currentPhase"),
      phase2: "Fase " + currentPhase
  }
});

Upvotes: 1

Views: 1531

Answers (2)

MorganIsBatman
MorganIsBatman

Reputation: 1010

For such cases you would make use of a computed property:

import Controller from '@ember/controller';
import { computed } from '@ember/object';

export default Controller.extend({
  currentPhase: 1,

  strings: computed('currentPhase', function() {
    let currentPhase = this.get('currentPhase');
    return {
      title: "Title",
      phase1: `Phase ${currentPhase}`,
      phase2: `Phase ${currentPhase}`
    }
  }
});

Upvotes: 2

Ahmet Emre Kilinc
Ahmet Emre Kilinc

Reputation: 6895

In your case, you have defined selfReference in your init function, but you tried to reach it from outside of the function which is forbidden. In order to reach it from outside the function, you need to set it to a variable by using set function. You can consider defining strings as computed property as well. Take a look at this twiddle.

Upvotes: 0

Related Questions