Reputation: 27384
Using AngularJS Components what is the best way to signal to a component to update?
Say I have myComponent
and I want to tell it to update its data, how would I achieve that? I'd prefer not to use $emit
or $broadcast
if possible instead opting for something as analogous to Angular2 as possible.
Currently I pass in a control object with callbacks that the component implements but I do not like this approach.
Another concept I had was to signal via the one-way binding mechanism but it feels very hacky.
<my-component update="$ctrl.shouldUpdate"></my-component>
My controller would then do
function update(){
this.shouldUpdate = Math.rand();
}
Is there a better, more modern Angular way to do this?
Clarification
Some people asked for clarification:
Imagine you have two components
Because of how they are used, they both get a list of "people" from the server so have no shared (bound), common list of people.
Imagine then that the personEditor changes a persons name and saves it to the server.
How would one go about telling the peopleList component that it needs to update
Upvotes: 2
Views: 1281
Reputation: 6486
This sounds like the perfect time for a service that is responsible for getting a list of people from the server. Both of your pieces would use the same service to get information. Then if one updates something, the other (which is using the same data source) would automatically see the updates. For example:
angular
.module('app')
.service("peopleService", peopleService);
peopleService.$inject = ["$http"];
function peopleService($http) {
var svc = this;
svc.people = [];
svc.getPeople = getPeople;
svc.updatePerson = updatePerson;
return svc;
function getPeople() {
//$http call to get people
}
function updatePerson(person) {
//some call to the server
//update the javascript objects
}
}
Then both of your peopleEditor
and peopleList
can reference the same data source. Just include the peopleService
into the controller(s) and use that as the data source. For example:
angular
.module('app')
.controller('mainController', mainController);
mainController.$inject = ['peopleService'];
function mainController(peopleService) {
var vm = this;
vm.people = peopleService.people;
return vm;
}
Upvotes: 0
Reputation: 5176
In the person editor component I would add an optional reference to the parent list using bindings. Something like:
bindings: { parentList: '<?' }
Then when you update in the person editor component check for the presence of parentList and update accordingly. You could set it up so you specify the method in the parent to call and pass it the updated data.
Upvotes: 1