How To Access $rootscope Variable From Directive Templateurl
I've managed to get cross-domain HTML templates working by applying a url to the rootScope which I can access from controllers and other HTML files, but the problem arises when it
Solution 1:
You can use angular's dependency injection at directive level - so just place $rootScope
there. See my example below:
angular
.module('bertha')
.directive('bthToggleHeader', ['$rootScope', function($rootScope) {
var controller = [
'$scope', '_',
function($scope, _) {
if ($scope.tglOpen)
$scope.tglShowSection = true;
$scope.toggleShowSection = function() {
$scope.tglShowSection = !$scope.tglShowSection;
};
}
];
return {
restrict: 'E',
scope: {
tglHeading: '@',
tglShowSection: '=',
tglOpen: '=?'
},
transclude: true,
controller: controller,
templateUrl: $rootScope.cdnUrl + '/html/directives/bthToggleHeader.html'
};
}]);
As Joe Clay said, $rootScope
exists only in the controller function - that's why it's undefined outside of it.
Solution 2:
$rootScope
has fallen out of scope by the time you try to access it in templateUrl
- you can't use a function parameter outside of the function (or at least, not without saving a reference somewhere)!
var controller = [
"$scope", "$rootScope", "_", function ($scope, $rootScope, _) {
if ($scope.tglOpen)
$scope.tglShowSection = true;
$scope.toggleShowSection = function() {
$scope.tglShowSection = !$scope.tglShowSection;
};
} // FUNCTION ENDS HERE - past this point $rootScope is undefined!
];
EDIT: While this answer gives some context on why your current code doesn't work, I wasn't 100% sure of the best way to solve the problem - Cosmin Ababei's answer seems like an effective solution, and I'd recommend you follow his advice!
Post a Comment for "How To Access $rootscope Variable From Directive Templateurl"