Why can't the $rootScope be accessed in the template of a directive with isolate scope?
You can try this way out using $root.blah
Working Code
html
<label ng-click="test($root.blah)">Click</label>
javascript
angular.module('app', [])
.controller('Ctrl', function Ctrl1($scope, $rootScope) {
$rootScope.blah = 'Hello';
$scope.yah = 'World'
})
.directive('myTemplate', function() {
return {
restrict: 'E',
templateUrl: 'my-template.html',
scope: {},
controller: ["$scope", "$rootScope", function($scope, $rootScope) {
console.log($rootScope.blah);
console.log($scope.yah);
$scope.test = function(arg) {
console.log(arg);
}
}]
};
});
Generally, you should avoid using $rootScope
to store values you need to share between controllers and directives. It's like using globals in JS. Use a service instead:
A constant (or value ... use is similar):
.constant('blah', 'blah')
https://docs.angularjs.org/api/ng/type/angular.Module
A factory (or service or provider):
.factory('BlahFactory', function() {
var blah = {
value: 'blah'
};
blah.setValue = function(val) {
this.value = val;
};
blah.getValue = function() {
return this.value;
};
return blah;
})
Here is a fork of your Fiddle demonstrating how you might use either
1) Because of the isolate scope $scope
in your controller Ctrl and in the directive controller don't refer to the same scope - let's says we have scope1 in Ctrl and scope2 in directive.
2) Because of the isolate scope scope2 do not prototypicallly inherit from $rootScope
; so if you define $rootScope.blah
there is no chance you can see it in scope2.
3) What you can access in your directive template is scope2
If I sum it up, here is the inheritance schema
_______|______
| |
V V
$rootScope scope2
|
V
scope1
$rootScope.blah
> "Hello"
scope1.blah
> "Hello"
scope2.blah
> undefined