0

I have two controllers, one controller being for a form, which is called when the form's button is clicked, and one controller being for a div, which is interpollated using scope and {{}}. The problem is that I need to pass the data collected after the form is submitted to the other controller. How can I call that second controller's function within the first controller's function:

//FIRST CONTROLLER, CALLED BY CLICKING BUTTON
app.controller('FormController', function ($scope) {
    $scope.IdSubmitted = function () {
        $scope.datatokens = json_datatokens;
        //WHERE I NEED TO CALL THE SECOND CONTROLLER, AND PASS IT "json_datatokens"
    }
});

//SECOND CONTROLLER
app.controller('#10Controller', function ($scope) { 

    $scope.datatokens = json_datatokens;    
});

HTML:

#FORM
<div ng-controller="FormController">
    <form class="search-wrapper" onsubmit='load_button();fetch_data();return false;'>
        <input type="text">
        <button type="submit" class="button " ng-click="IdSubmitted()">Submit Info</button>
    </form>

#DIV
        <div ng-controller='#10Controller' ng-init="init()">
            <p>Your payment is {{datatokens["DB.PMT"]}}</p>
        </div>
maudulus
  • 10,627
  • 10
  • 78
  • 117
  • Possible duplicate of http://stackoverflow.com/questions/9293423/can-one-controller-call-another-in-angularjs – runTarm Aug 12 '14 at 19:15

2 Answers2

1

there are a couple of options-

  1. use a shared object (I prefer a factory; you could go with a service as well) which both controllers reference. have the 1st controller set the data in that shared object, and the second one can read it.
    for example-

    app.factory('sharedStuffFactory', function() {
      return {
         sharedData: null; //that will be filled be one of the controllers
      }
    });
    

app.controller('FormController', function ($scope, sharedStuffFactory) { $scope.IdSubmitted = function () { $scope.datatokens = json_datatokens; sharedStuffFactory.sharedData = json_datatokens; } }); app.controller('#10Controller', function ($scope, sharedStuffFactory) { $scope.datatokens = sharedStuffFactory.sharedData;
});

  1. if you change your html structure a little to put the second div inside the first one, you could simply share a scope between them.
J. Ed
  • 6,692
  • 4
  • 39
  • 55
1

In addition to the options suggested by sJhonny, you could use broadcasting with something like the following.

app.controller('FormController', function ($scope) {
    $scope.IdSubmitted = function () {
        $scope.$emit('formSubmission', json_datatokens);
    }
});

app.controller('#10Controller', function ($scope) { 
    $scope.$on('formSubmission', function(event, data) {
        $scope.datatokens = data;
    });  
});
Andrew Sula
  • 939
  • 8
  • 24