Angularjs - $rootScope in directive link function

后端 未结 6 584
庸人自扰
庸人自扰 2021-01-30 10:57

I am asking this question because I am not quite clear on how to think of rootscope as a dependency passed to directives

I have a directive that needs to display some in

6条回答
  •  有刺的猬
    2021-01-30 11:00

    After laboring away on this same question for quite some time, I thought it was worth noting something that was neglected in the first post. Here is my original code:

    app.directive('countrymap', function() 
    {
        return {
            link: function(scope, element, attrs) {
                scope.$watch("countryMap", function (newCountry, oldCountry) 
                {
                    setTimeout( function() 
                    {
                        //function body here    
                    }, 100);
                })
            }
        };  
    }]);
    

    Aside from the more philosophical design question of whether or not you should even use $rootScope at all, there is one blatantly wrong thing with my code above that I feel was left out from Mike's solution - the reference to $rootScope. If you're like me and have segregated your directive and controller files you will need to modify your code as follows:

    app.directive('countrymap', ['$rootScope', function($rootScope) 
    {
        return {
            link: function(scope, element, attrs) {
                $rootScope.$watch("countryMap", function (newCountry, oldCountry) 
                {
                    setTimeout( function() 
                    { 
                        //function body here
                    }, 100);
                })
            }
        };  
    }]);
    

    Yet, there is still one more nagging question: can I accomplish the same goal without referencing $rootScope in the directive? Indeed you can. You need to broadcast the change to the $rootScope property effectively letting all child scopes know about the change and watching for this change in the directive.

    Controller:

    $rootScope.countryMap = 'thiscountry_map';
    $rootScope.$broadcast( "countryMapChanged", $rootScope.countryMap );
    

    Directive:

    app.directive('countrymapalt', [function() 
    {
        return {
            link: function(scope, element, attrs) {
                scope.$on("countryMapChanged", function(event, map) 
                {
                    setTimeout( function() 
                    { 
                        //function body here
                    }, 100);
                })
            }
        };  
    }]);
    

提交回复
热议问题