maudulus
maudulus

Reputation: 11035

Use Angular ngClick to call function assigned to a different controller

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>

Upvotes: 0

Views: 1024

Answers (2)

Andrew Sula
Andrew Sula

Reputation: 939

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;
    });  
});

Upvotes: 1

J. Ed
J. Ed

Reputation: 6742

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.

Upvotes: 1

Related Questions