0

I have two controller - controller1 and controller2.

app.controller('Controller1', function($scope) {

$scope.setItems=function()
{
    var itemName='Lemon';
}

});

app.controller('Controller2', function($scope) {
     //This controller i want da get 'itemName' from 'controller1'
});

How to get Data from controller2 to controller1. I apologize that my example is simple, but I want to figure it out

3 Answers3

2

https://docs.angularjs.org/guide/services

Controllers, as a rule, should not be aware of anything other than the objects they, themselves, are manipulating. Services are what allows your application to pass objects between controllers, as services persist through the application, where controllers are destroyed and re-started on a repeated basis.

app.controller('Controller1', ['ItemService1',function($scope, itemService) {

$scope.setItems=function()
{
    var itemName='Lemon';
   itemService.AddItem(itemName);
}

}]);

app.controller('Controller2', ['ItemService1', function($scope, itemService) {
     //This controller i want da get 'itemName' from 'controller1'
var lemons = itemService.getLemons();
}]);
Max Sorin
  • 1,042
  • 6
  • 14
0

its a bad design to be in one controller and access variables or methods in another controller. You can use services to do this job. Assign data to services so it can be share/access by multiple controllers/services in your application.

oseintow
  • 7,221
  • 3
  • 26
  • 31
0

Angular controller can't share state with another controller unless you inject it somehow. Generally for sharing controllers state it is best practice to use factory, service or $rootScope in this exact order.

Nhor
  • 3,860
  • 6
  • 28
  • 41