0

I want to send the result of a function to a parent controller from a child.

Here is my file structure

-submission.controller.js
--calculate.controller.js

In calculate.controller.js i have a function that looks like:

function validForm() {
  var checkForm = false;
  if(files === true) {
    checkForm = true;
  }
  return checkForm;
}

and i want to send the results of this function to the parent (submission.controller.js) and use it as an argument in a function.

showValidZip() {
  if (validForm() === true) {
    return false;
  }
  return true;
};

So far i've tried to use $emit and $on to send validForm from calculate to submission but havent had much luck in doing so.

for example:

$scope.$emit('validForm', function () {
  var checkForm = false;
  if(files === true) {
    checkForm = true;
  }
  return checkForm;
});

and

$scope.showValidZip = function () {
  if ($scope.$on('validForm') === true) {
    return false;
  }
  return true;
};

but it's not really working as intended.

zomdar
  • 263
  • 2
  • 6
  • 22
  • Possible duplicate of [Working with $scope.$emit and $scope.$on](https://stackoverflow.com/questions/14502006/working-with-scope-emit-and-scope-on) – Jonathan Brizio Dec 04 '17 at 18:05
  • File structure doesn't really matter. The way the controllers are used is. Please, explain what 'it's not really working as intended' exactly means and provide http://stackoverflow.com/help/mcve that can replicate the problem. – Estus Flask Dec 04 '17 at 18:41
  • You have to use `$rootscope` and also you have inverted `emit` and `on` syntax. – Vipin Kumar Dec 04 '17 at 18:41

2 Answers2

0

Assuming the controllers are used in such a way that they are parent-child of each other, you have two issues with the code you have provided:

  1. $scope.$emit expects arguments next to event name so if you want to pass a function's result, you can have a seperate function and then call it from there like $scope.$emit('validForm', myFunctionCall())
  2. Also, you can't use $scope.$on like that since it doesn't return anything. If you want to access the values sent from $emit, you can do that inside the listener function (second argument) i.e. something like this:

    $scope.$on('validForm', function(event, argument1) {
      // argument1 is the same as return value of myFunctionCall()
    });
    
tanmay
  • 7,761
  • 2
  • 19
  • 38
0

'Emit' from child.

$scope.$emit('validForm', function () {
var checkForm = false;
if(files === true) {
checkForm = true;
}
return checkForm;
});

Now Receive.

$scope.showValidZip = function () {
$scope.$on('validForm'), function(event, data) {
  if(data === true)
  return false;
});
return true;
};
Anj D
  • 92
  • 3