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
  • 2
    Ideally for this kind of situation, you should create service/factory to share data between two controllers Commented Feb 26, 2016 at 21:41
  • If your no problem, please example! Commented Feb 26, 2016 at 21:43
  • ok, controller to controller isnt valid from pattern , for you issue , you can use , factorys, services, rootscope, localstorage, $swatch, $.emit Commented Feb 26, 2016 at 21:44

3 Answers 3

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();
}]);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.