简体   繁体   中英

Accessing angular's rootScope from within a directive template

I have seen some suggestions on trying to achieve this, but I can't seem to find a direct solution to what I need.

I have certain values stored in arrays and objects in the rootScope in my app, I would like to be able to access these from different directives templates in my project.

You need to inject the $rootScope into your directive as following,

myApp.directive('testDirective', function($rootScope) {
  template: '<div>Rootscope value for name is '+ $rootScope.name+'</div>'
  //other directive code
});

You will be then able to access the $rootScope values inside the directive template or even inside the template referenced by templateUrl

The simplest way I could think of would be to use rootScope in your directive and store a reference to the object you need on the directive's own scope. You could then access it like any other item on your directive's scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM