如何从编译器函数指令中访问作用域?

4
我有一个基于发送的数组属性构建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){

            }
        }
    }
});

Thank

1个回答

5

在编译函数返回的LinkingFunction之前,您将无法访问作用域。编译函数创建html模板。在LinkingFunction期间,作用域会与模板进行组合

我不确定您试图做什么,但与其深入到编译函数中,我建议使用链接函数上的标准template或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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接