-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 ?

4
  • can you share your code ? Commented Jun 15, 2016 at 10:40
  • 1
    you could use $rootScope, if both controllers falls within one module Commented Jun 15, 2016 at 10:43
  • 1
    "doesn't seem efficient" ... huh? Why not? Why would you try to re-invent the wheel and go against convention? Commented Jun 15, 2016 at 10:51
  • 1
    @code9215 there is only one rootScope regardless of how many modules get injected into main app module Commented Jun 15, 2016 at 10:53

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I never used "as" feature fro controller names. looks like interesting thing to try. Thanks for the reply.
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.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.