Search code examples
angularjsscopeparent

Angular parent child scope with service


I'm stuggling with some concepts of Angular, in particular the flow of variable and scope.

What I'm trying to do is to set a variable in a child controller and pass it to a parent scope. Consider this simple example:

module.controller('childController', childController);
function childController($scope,$http,$window, hexafy) {
    $scope.hex = hexafy.myFunc(17);      
}

module.controller('parentController', parentController);
function parentController($scope, hexafy) {

}

module.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});

Then my mark-up is as follows:

{{hex}}

<section data-ng-controller="listingsViewController">....</section>

The calculation is handled by the child controller but as you can see I want to pass the variable to the 'parent'. I have read about 'parent' scope but I understand that this is not best practise so I'm attempting to use a service. Where am I going wrong?


Solution

  • There are many different ways to achieve this and I would actually recommend following approach (using common $scope object variable in both parent and child controller) instead of using service as it is much easier and cleaner approach.

    You can then access the hex value in parent controller using $scope.shareValue.hex.

    module.controller('childController', childController);
    function childController($scope,$http,$window, hexafy) {
        $scope.shareValue.hex = hexafy.myFunc(17);
    }
    
    module.controller('parentController', parentController);
    function parentController($scope, hexafy) {
        var shareValue = {
           hex: ''
        };
        $scope.shareValue = shareValue;
    }
    

    ====================================================================== Updated with using service:
    Please refer to Matthew Cawley post on comment below.