2015-02-11 124 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