martes, 26 de abril de 2016

AngularJS: Registering child scope with parent to be able to make synchronous calls

Hi!

I had been looking for a way to be able to "send messages" from parent scope to a child. Doing the opposite is very simple:

Just call a parent scope's method from child scope and you'll be done.

But doing the opposite could be tricky. There are ways to go around it (using a common service, using watchers). Here I will explain one method that I've been able to use:

Registering child scope with parent.

Suppose you have a child controller like this:

blah.controller('ChildController', function($scope) {

    $scope.methodToCall = function(aString) {
        console.log(aString);
    }
});


From a parent fragment controller you won't be able to call the method because that $scope is not the same as the child fragment's:

blah.controller('ParentController', function($scope) {

    /**
     * Some event somewhere
     */
    $scope.someClick = function() {
        $scope.methodToCall('Hello'); // wont work!!!
    }

});

Good luck with that.

But how about we allow the child controller to register itself so the parent scope holds the instance of the child scope?

blah.controller('ChildController', function($scope) {

    // register child node with parent
    $scope.registerChildNode($scope);

    $scope.methodToCall = function(aString) {
        console.log(aString);
    }
});

And then on the parent:

blah.controller('ParentController', function($scope) {

    $scope.childScope = null;
    $scope.registerChildNode = function(childScope) {
        $scope.childScope = childScope;
    }

    /**
     * Some event somewhere
     */
    $scope.someClick = function() {
        if ($scope.childScope == null) {
            return;
        }

        // call child scope method
        $scope.childScope.methodToCall('Hello');
    }

});

That should work! Best regards!

No hay comentarios:

Publicar un comentario