如何从指令templateUrl访问$ rootScope变量

时间:2016-03-15 09:30:33

标签: javascript angularjs angularjs-directive

我已经设法通过将一个url应用到rootScope来获取跨域HTML模板,我可以从控制器和其他HTML文件访问它,但是当从指令访问模板时会出现问题。这是我的指令代码:

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。有什么明显的东西我在这里做错了吗?

在一个工作项目中,我们尝试使用链接功能但是根本没有完全缩小,因此控制器方法。

任何帮助将不胜感激!感谢。

2 个答案:

答案 0 :(得分:2)

当您尝试在$rootScope中访问它时,

templateUrl已超出范围 - 您无法在该功能之外使用函数参数(或者至少,不是没有保存参考某处)!

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的答案似乎是一个有效的解决方案,我建议你听从他的建议!

答案 1 :(得分:2)

您可以在指令级别使用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只存在于控制器功能中 - 这就是为什么它在它之外是未定义的。

相关问题