Sergey Kopylov Sergey Kopylov - 1 month ago 4
AngularJS Question

How to change data into Angular 1.5 Component via an external Service?

I make an app with Angular 1.5 Components. I provide a data into component via

resolve
parameter, in that way I can display any data from different sources in the same component. But I don't understand, how to change some data in my component.

For example, I have a User service, which works with users through the API. In my state I load a component and use method Users.get(). I use UI Router.

//...
$stateProvider
.state('users', {
url: '/users',
component: 'formPage',
resolve: {
values: function(Users) {
return Users.get();
});
//...

//...
component('formPage', {
bindings: {
values: '<'
},
//...


I have a form in this component and want to change the data. I want to call Users.update() method, when form will be submitted. But the component don't know anything about Users service and that's right.

How i may specify that component must use Users.update() for update the data in this state? And how I call this method in the component when form will be submitted?

Answer
resolve: {
  values: function(Users) {
    return Users.get();
  },
  onUpdate: function(){
    return Users.update.bind(Users);
  }
);

bindings: {
    values: '<',
    onUpdate: '<'
},

and you can call it like $ctrl.onUpdate(data).then(...

Comments