Reputation: 121
There's a plethora of information regarding getting data from a service and using it in the controller, but I have scoured the internet and found no examples of or explanations on how to do this. If I have a basic controller:
app.controller('myController', function($scope) {
$scope.myObject = [
{
x = 1;
y = 2;
},
{
x = 3;
y = 4;
}]
});
I would like to write a service that would take the object "myObject" from the controller, alter the object, and send it back to the controller. I understand how to write services and get the information TO a controller, but how can a service access the object "myObject"?
Upvotes: 0
Views: 473
Reputation: 2692
You have to :
1) Create the service and the function which modifies the data. 3) Inject the service in your controller. 4) Call your service's function.
Check out this example I've wrote down for you.
You've got the controller:
.controller("MyController",function($scope, ModifyDataService) {
$scope.data = "foo";
$scope.dataModified = null;
$scope.modifyData = function() {
$scope.dataModified = ModifyDataService($scope.data);
}
})
And the service which modifies the data:
.service("ModifyDataService", function() {
return function(data) {
/** Reverse String **/
if(typeof data !== 'string') throw 'Data must be string';
return Array.from(data).reverse().join("");
};
})
Upvotes: 1
Reputation: 706
If your use case just involves altering an object, then perhaps a service method is the answer.
app.controller('myController', function($scope, myService) {
$scope.myObject = [{
x = 1;
y = 2;
}, {
x = 3;
y = 4;
}];
/* Option 1, transform object in place. */
myService.changeObject( $scope.myObject );
/* Option 2, replace object. */
$scope.myObject = myService.changeObject( $scope.myObject );
});
Upvotes: 1