[英]How to access $rootScope variable from directive templateUrl
我已經設法通過將URL應用於rootScope來使跨域HTML模板正常工作,我可以從控制器和其他HTML文件訪問該URL,但是從指令訪問模板時會出現問題。 這是我的指令代碼:
angular.module("bertha")
.directive("bthToggleHeader", function() {
var controller = [
"$scope", "$rootScope", "_", function ($scope, $rootScope, _) {
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"
};
});
嘗試此操作時,我得到: ReferenceError: $rootScope is not defined
。 有什么明顯的證據表明我在這里做錯了嗎?
在一個工作項目中,我們嘗試使用鏈接功能,但是在最小化方面並不能很好地發揮作用,因此采用了控制器方法。
任何幫助將不勝感激! 謝謝。
當您嘗試在templateUrl
訪問$rootScope
時,其范圍已超出范圍-您不能在函數外部使用函數參數(或者至少在沒有將引用保存在某個地方的情況下)!
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!
];
編輯:雖然此答案提供了有關您當前代碼為何不起作用的一些背景信息,但我不確定100%確定解決問題的最佳方法-Cosmin Ababei的答案似乎是有效的解決方案,我建議您遵循他的建議!
您可以在指令級別使用angular的依賴項注入-因此只需將$rootScope
放在此處即可。 請參閱下面的示例:
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'
};
}]);
如Joe Clay所說, $rootScope
僅存在於控制器函數中-這就是為什么在其外部未定義它的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.