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



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

代码是这样的:

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

谢谢

在编译函数返回LinkingFunction之前,您将无法访问作用域。compile函数创建html模板。在linkfunction中,作用域是与模板组合在一起。

我不确定你想做什么,但我会在链接函数上使用标准模板或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

最新更新