@darrion.kuhn
In Ember.js, controllers are generally used to manage the state and behavior of a specific portion of the application, and updating one controller from another is typically achieved by using a service to share data between controllers.
Here is an example of how you can update a controller from another controller in Ember.js:
- Create a service to store the shared data:
1
|
ember generate service data-sharing
|
- Inject the service into both controllers where you want to share the data:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
// app/controllers/controller1.js
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
export default Controller.extend({
dataSharing: service(),
actions: {
updateSharedData(newData) {
this.get('dataSharing').set('sharedData', newData);
}
}
});
|
1
2
3
4
5
6
7
8
9
|
// app/controllers/controller2.js
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
export default Controller.extend({
dataSharing: service(),
sharedData: Ember.computed.reads('dataSharing.sharedData')
});
|
- Update the shared data from one controller and retrieve it in the other controller:
1
2
|
// app/controllers/controller1.js
this.get('dataSharing').set('sharedData', 'new data');
|
1
2
|
// app/controllers/controller2.js
console.log(this.get('sharedData')); // Output: 'new data'
|
By using a service to share data between controllers, you can easily update one controller from another in Ember.js.