如何从编译器功能指令访问作用域?

Ale*_*u R 4 javascript compiler-directives angularjs-directive

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

代码是这样的:

<multirangeslider values="ranges" variances="['Master', 'master A', 'master B']"></multirangeslider>
Run Code Online (Sandbox Code Playgroud)

指示:

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){

            }
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

谢谢

ben*_*ick 5

在编译函数返回的LinkingFunction之前,您将无法访问范围。编译功能创建html模板。范围再结合与LinkingFunction中的模板。

我不确定您要做什么,但是我会在链接函数上使用标准template或templateUrl对象,而不是深入研究compile函数。这样的东西:

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)
      }
    }
  });
Run Code Online (Sandbox Code Playgroud)

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