-1

I have two controllers... C1 and C2, I want to verify a data that I have in C1 but the verification logic is in C2, So how can I pass that data from C1 to C2 and get back the result in C1 ?

I am aware of the services in angular, but for that communication I have to pass all data [Which is too large] from C1 and C2 to service which doesn't seem efficient. Any optimized way to do so ?

Charlie
  • 22,886
  • 11
  • 59
  • 90
Maxx32
  • 25
  • 5

4 Answers4

2

Here are two options if you don't want to use a common service.

  1. You can use $rootScope to save your shared data.

  2. You can get the access to the scope of C1 from C2 by selecting an element that comes under C1.

Lets say <div id="myC1Candidate"> is under C1. You can do the following to get the scope of C1 from C2

angular.element(document.getElementById("myC1Candidate")).scope()

Note

It is wrong to think that using a service is inefficient when you have to share large amount of data. The data is shared by reference when you assign it to a service singleton.

Charlie
  • 22,886
  • 11
  • 59
  • 90
2

1- You have to use a service.

2- If you don't want to then nested controllers inherit scope:

<div ng-app="myApp">
  <div ng-controller="Ctrl1 as c1">
    <div ng-controller="Ctrl2 as c2">
      {{c1.name}}
    </div>
  </div>
</div>

3- Inside controller code you can use the $controller service:

.controller('C2', function($scope, $controller) {
    $controller('C1', {$scope: $scope});
});

4- Don't use $rootScope to store data.

gyc
  • 4,300
  • 5
  • 32
  • 54
  • I never used "as" feature fro controller names. looks like interesting thing to try. Thanks for the reply. – Maxx32 Jun 15 '16 at 11:51
0

You can register those C1/C2 controllers in the parent controller and use it as a proxy.

Ref. AngularJS access parent scope from child controller

Community
  • 1
  • 1
hsz
  • 148,279
  • 62
  • 259
  • 315
0

you can do that with

Controller 2 (don't forget to inject $rootScope as dependency to your controller):

$rootScope.$broadcast("notifyC1",{/*mydata*/});

Controller 1:

$scope.$on("notifyC1",function(evt,data){
  console.log(data)
});

but you should really rethink your application design if you have to do that. Store that data and the verification logic in a service and inject it to your controllers.

ManuKaracho
  • 1,180
  • 1
  • 14
  • 32