2015-02-11 119 views
0

我想寫一個指令,它接受一個範圍變量名稱併爲其分配一個不同的命名參數傳遞給一個函數的結果。下面,files="result"旨在在glob隔離範圍內創建一個{{result}}變量。 「matching」變量的內容將在父上下文中進行評估,並分配給隔離變量「matching」。角度指令與隔離範圍,字段無法訪問

該指令然後調用一個函數,最終分配給文件指向的隔離變量(result這裏)返回的數組。 {{result}}的擴展然後可以用於例如ng-repeat

該指令應該是可重用的,無需更改變量名稱。

這沒有發生。如果我將所有內容都分配給父項,我可以使其工作,但每次都需要更改變量名稱。

angular.module('j20-glob', ['api']) 
/* 
* usage: <glob files="result" matching="/bin/{{prefix}}*"> 
*   {{result}} 
*   </glob> 
*  should allow another just after the first without stomping result 
*  <glob files="result" matching="/something">{{result}}</glob> 
*/ 

.directive('glob', ['$parse', 'api', function($parse, $api) { 
    return { 
    priority: 99, // it needs to run after the attributes are interpolated  
    restrict: 'AE', 
    scope: { 

    }, 

    link: function(scope, iElement, iAttributes) { 

     var indexModel = $parse(iAttributes.files); 
     iAttributes.$observe('matching', function(value) { 
      if (!value) 
      return; 
      $api.glob(value).then(function(res) { 
       indexModel.assign(scope, res); 
      // indexModel.assign(scope.$parent, res); 
      }); 
     }); 
     } 
    } 
    } 
]); 
+0

Plunker /小提琴/ CodePen可能? – 2015-02-11 19:42:02

回答

0

如果我在這裏理解你的代碼,你有一個類似的問題我回答在這裏:Directive doesn't work when I which the version of Angular to 1.0.1 to 1.2.27

您已創建元素指令,名爲glob。該指令有一個隔離範圍,在您的示例中,您附加了一個屬性result。這一切工作正常。問題是,隔離範圍內的屬性只能在指令中訪問;在你的情況下,你試圖在指令之外訪問它。

元素<glob></glob>是你的指令。此元素可以是其他元素的容器,例如角度表達式{{result}},但這些元素不是指令的一部分,因此不在範圍內。

如果您要包含模板並將{{result}}放置在模板中,您會看到預期結果。但是,如果你改變你傳遞變量這個停止工作

使用transclude功能的工作指令的草稿可能是這樣的:

.directive('glob', ['$parse', 'api', function($parse, $api) { 
    return { 
    priority: 99, // it needs to run after the attributes are interpolated  
    restrict: 'AE', 
    scope: { 

    }, 
    transclude : true, 
    link: function(scope, iElement, iAttributes, ctrl, transclude) { 

     var indexModel = $parse(iAttributes.files); 
     iAttributes.$observe('matching', function(value) { 
      if (!value) 
      return; 
      $api.glob(value).then(function(res) { 
       indexModel.assign(scope, res); 
      // indexModel.assign(scope.$parent, res); 
      }); 
      //append our scope into the DOM element (clone) instead of $scope 
      transclude(scope, function(clone, scope){ 
       element.append(clone); 
      }); 
     }); 
     } 
    } 
    } 
]); 
+0

例如,我試圖在ng-repeat中獲得索引變量的效果。 '

  • {{i}}
' '只有在指令中關閉,否? 我也嘗試將''中的所有內容都包括進去,但是這也不能做到。 – 2015-02-13 00:59:38

+0

你很可能不得不使用transclusion;看到http://angular-tips.com/blog/2014/03/transclusion-and-scopes/ – Claies 2015-02-13 01:01:14

+0

的'NG-repeat'指令不使用一個孤立的範圍,它會創建一個子範圍。 – Claies 2015-02-13 01:04:17