如何从指令templateUrl访问$ rootScope变量 [英] How to access $rootScope variable from directive templateUrl

查看:88
本文介绍了如何从指令templateUrl访问$ rootScope变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设法通过将URL应用于rootScope来使跨域HTML模板正常工作,我可以从控制器和其他HTML文件访问该URL,但是从指令访问模板时会出现问题.这是我的指令代码:

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 comes to accessing the template from a directive. Here's my directive code:

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.有什么明显的证据表明我在这里做错了吗?

When attempting this I get: ReferenceError: $rootScope is not defined. Is there something blatantly obvious that I'm doing wrong here?

在一个工作项目中,我们尝试使用链接功能,但是在最小化方面并不能很好地发挥作用,因此采用了控制器方法.

In a work project we tried using the link function but that didn't play nicely with being minified at all, hence the controller approach.

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

Any help would be greatly appreciated! Thanks.

推荐答案

您可以在指令级别使用angular的依赖项注入-只需将$rootScope放在此处即可.请参阅下面的示例:

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'
    };
  }]);

正如Joe Clay所说,$rootScope仅存在于控制器功能中-这就是为什么它在其外部未定义的原因.

As Joe Clay said, $rootScope exists only in the controller function - that's why it's undefined outside of it.

这篇关于如何从指令templateUrl访问$ rootScope变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆