【问题标题】:How to access scope from compiler function directive?如何从编译器函数指令访问范围?
【发布时间】:2013-05-04 22:38:59
【问题描述】:

我有一个基于作为属性发送的数组构建 html 的指令。我无法从指令的编译器函数访问它。它在链接函数中工作,但我需要在编译中,否则新模板不会被编译。

代码是这样的:

<multirangeslider values="ranges" variances="['Master', 'master A', 'master B']"></multirangeslider>

指令:

angular.module("vtApp.directives").
directive('multirangeslider', function ($parse, $timeout, $compile) {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            values: "=",
            options: "=",
            variances: "&" 
        },
        compile: function (element, attrs) {
            var htmlText, variances, values;
            variances = eval(attrs.variances);

            values = scope.ranges //scope is undefined
            values = eval (attrs.variances) //returns string "ranges"
            values = ???  ///what should I put here?

            htmlText = '<div></div>';
            element.replaceWith(htmlText);
            return function (scope, element, attrs){

            }
        }
    }
});

谢谢

【问题讨论】:

    标签: javascript angularjs-directive compiler-directives


    【解决方案1】:

    在您的编译函数返回 LinkingFunction 之前,您将无法访问范围。 compile 函数创建 html 模板。然后在 LinkingFunction 期间范围与模板组合

    我不确定您要做什么,但我会在链接函数上使用标准模板或 templateUrl 对象,而不是深入到编译函数中。像这样的东西:

    angular.module("vtApp.directives").
      directive('multirangeslider', function ($parse, $timeout, $compile) {
        return {
          restrict: 'E',
          replace: true,
          template: "<div ng-repeat='val in values'>{{val}}</div>", //Your template code
          scope: {
            values: "=",
            options: "=",
            variances: "&" 
          },
          link: function (scope, element, attrs) {
            scope.values = eval(attrs.variances)
          }
        }
      });
    

    您可以在此处找到有关如何构造指令的更多信息: https://github.com/angular/angular.js/wiki/Understanding-Directives

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多