0

I have two controllers (Main controller and Child controller). I am trying to pass value from Main to Child controller.

Here are the controllers:

.controller('mainController', ['$scope', '$rootScope', '$location', 'CIFactory', function ($scope, $rootScope, $location, CIFactory) {

    $scope.moveTool = function (buildServerTool) {  //Am calling this moveTool function from View
        $scope.tool = buildServerTool.toolname;
        $scope.$broadcast('update_parent_controller', $scope.tool);
    };
}])

.controller('childController', ['$scope', '$rootScope', '$q', '$timeout', '$log', 'CIFactory', function ($scope, $rootScope, $q, $timeout, $log, CIFactory) {

    $scope.$on('update_parent_controller', function (event, tools) {
        $scope.tools = tools;
    });
}])

When I debug, control is going in moveTool() function, but it is not going inside $on(i.e., value in tools is not assigned to $scope.tools. What am I doing wrong here ?

Shaohao
  • 3,471
  • 7
  • 26
  • 45
user2439278
  • 1,222
  • 7
  • 41
  • 75

2 Answers2

1

As Martijn said $broadcast moves down the $scope chain, so it may be best to use $rootScope if the child controller isnt directly inside the parent scope

$rootScope.$broadcast('update_parent_controller', $scope.tool);

See this answer for more information on emit vs broadcast and scopes

Community
  • 1
  • 1
Chris
  • 26,744
  • 48
  • 193
  • 345
0

Thanks Chris. I have also tried another method and it worked for me. Instead of using $broadcast and $on, I just used following line in child controller,

   $scope.tools = $scope.$parent.tool;

So, the above code took the $scope value from parent controller and assigned to new scope $scope.tools, which I have used in corresponding View.

user2439278
  • 1,222
  • 7
  • 41
  • 75