Roland
Roland

Reputation: 9701

accessing parent scope inside a directive

I have this two directives, one nested inside each other :

<envato class="container content-view-container" data-ng-cloak data-ng-hide="spinner">
    <items data-ng-repeat="items in marketplaces"></items>
</envato>

And each of those two are defined as such :

Application.Envato.directive("envato", ["$timeout", function($timeout){

    var object = {

        restrict : "E",
        controller : "EnvatoAPIController",
        transclude : true,
        replace : true,
        templateUrl : "templates/envato-view.php",
        link : function(scope, element, attrs, controller) {

            console.log(scope);

            return controller.getLatestItems().then(function(data) {



                scope.marketplaces = angular.fromJson(data);
                scope.count = scope.marketplaces.length;

                var tst = angular.element(element).find(".thumbnails");

                /* $timeout(function() { scope.swiper = new Swipe(document.getElementById('swiper-container')); }, 5000); */                    
                scope.spinner = false;
            });

        }
    };

    return object;
}]);

Application.Envato.directive("items", function(){

    var iterator = [],
        object = {

            require : "^envato",
            restrict : "E",
            transclude : false,
            replace : true,
            templateUrl : "templates/envato-items-view.php",
            link : function(scope, element, attrs, controller) {

                iterator.push(element);

                if (iterator.length === scope.$parent.$parent.count) { console.log(iterator); };                                    
            }
        };

    return object;
});

A lot of the code above might not make a lot of sense because it's part of a bigger application, but I hope it does for my question. What I'm trying to do is to change a scope property of the directive envato from the directive items. Because I have a iteration and I want to know when it's done so I can do another operation on the appended DOM elements during that iteration.

For instance let's say I will have the scope.swipe defined inside the directive envato, and watch it for changes. In the directive items, I will watch when the ng-repeat is done and then change the above defined scope property scope.swipe. This will trigger the change inside the directive envato, and now I will know that I can do my operation.

I hope that I'm clear enough, if not I could try having more code or I'll try being more specific. How could I achieve what I just described above ?

EDIT : I do know that using : console.log(angular.element(element.parent()).scope()); inside the directive items will give me the scope of the envato directive, but I was wondering if there was a better way of doing it.

Upvotes: 3

Views: 5350

Answers (5)

sidonaldson
sidonaldson

Reputation: 25284

Hmmm it appears you are trying to make it difficult for yourself. In your directive you do not set a scope property:

var object = {
    restrict : "E",
    transclude : true,
    replace : true,
    scope: true,
    ...

Setting scope: {} will give your directive an fully isolated new scope.

BUT setting scope: true will give your directive a fully isolated new scope that inherits the parent.

I use this method to contain the model in the top level parent directive and allow it to filter down through all the child directives.

Upvotes: 1

Erich
Erich

Reputation: 2773

I love Mark's answer but I eventually created an attribute directive to save element directives' scopes to the rootScope like so:

myApp.directive('gScope', function(){
    return {
        restrict: 'A',
        replace: false,
        transclude: false,
        controller: "DirectiveCntl",
        link: function(scope, element, attrs, controller) {
            controller.saveScope(attrs.gScope);
        }
    }
});

...

function DirectiveCntl($scope, $rootScope) {
    this.saveScope = function(id) {
        if($rootScope.directiveScope == undefined) {
            $rootScope.directiveScope = [];
        }
        $rootScope.directiveScope[id] = $scope;
    };
}

...

<span>Now I can access the message here: {{directiveScope['myScopeId'].message}}</span>
<other-directive>
    <other-directive g-scope="myScopeId" ng-model="message"></other-directive>
</other-directive>

Note: While this makes it a snap to collect data from all your various directives it comes with my word of caution that now you have to ensure the potential pile of scopes are properly managed to avoid causing a memory leak on pages. Especially if you are using the ng-view to create a one page app.

Upvotes: 0

Mark Rajcok
Mark Rajcok

Reputation: 364697

For this kind of inter-directive communication, I recommend defining an API/method on your envato directive that your items directive can call.

var EnvatoAPIController = function($scope) {
    ...
    this.doSomething = function() { ... }
}

Your items directive already requires the envato directive, so in the link function of your items directive, just call the the API when appropriate:

require : "^envato",
link : function(scope, element, attrs, EnvatoCtrl) {
   ...
   if(scope.$last) {
       EnvatoCtrl.doSomething();
   }
}

What is nice about this approach is that it will work even if you someday decide to use isolate scopes in your directives.

The tabs and pane directives on the AngularJS home page use this communication mechanism. See https://stackoverflow.com/a/14168699/215945 for more information. See also John's Directive to Directive Communication video.

Upvotes: 4

Rajkamal Subramanian
Rajkamal Subramanian

Reputation: 6944

I think you are looking for a callback that gets called when the ng-repeat completes. If that's what you want, i have created a fiddle. http://jsfiddle.net/wjFZR/.

There is no much of UI in the fiddle. Please open the firebug console, and run the fiddle again. You will see an log. That log is called at the end of an ng-repeat defined in the cell directive.

$scope.rowDone = function(){ console.log($scope) } this is the callback function that is defined on the row directive that will get called when the ng-repeat of the cell directive is completed.

It is registered in this way.

<cell ng-repeat="data in rowData" repeat-done="rowDone()"></cell>

Disclaimer: I'm too a newbie in angularjs.

Upvotes: 1

Caio Cunha
Caio Cunha

Reputation: 23394

Use scope.$eval('count') at item directive and let angular resolve for you.

Upvotes: 1

Related Questions