簡體   English   中英

如何從編譯器函數指令訪問范圍?

[英]How to access scope from compiler function directive?

我有一個基於作為屬性發送的數組構建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){

            }
        }
    }
});

謝謝

在編譯函數返回的LinkingFunction之前,您將無法訪問范圍。 編譯函數創建html模板。 然后在LinkingFunction期間將范圍與模板組合

我不確定你要做什么,但我會在鏈接函數上使用標准模板或templateUrl對象,而不是潛入編譯函數。 像這樣的Somethig:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM