2013-05-04 125 views
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){ 

      } 
     } 
    } 
}); 

感謝

回答

4

您將無法訪問範圍,直到它由你的編譯函數返回的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