【问题标题】:Adding directive depending on scope value根据范围值添加指令
【发布时间】:2015-06-28 21:10:51
【问题描述】:

我在控制器范围内有一个数组,例如

$scope.data = [{
   "name" : "test",
   "type" : "test"
 },{
   "name" : "production",
   "type" : "production"
 }]

现在在视图中,我正在对模型数据执行循环,并且我有两个指令,一个是测试,另一个是生产。我想根据类型在 ng-repeat 中显示这些指令。所以我写了

<div ng-repeat="item in data">
  <test ng-if="item.type == 'test'"></test>
  <production ng-if="item.type == 'production'"></production>   
</div>

这东西很好用。但是我的问题是,除了添加这些 ng-if 之外,还有什么更好的方法,以便我可以根据模型的类型值在 dom 中添加这些指令。我试过了:

<{{item.type}}></{{item.type}}>

但显然它没有用。

【问题讨论】:

  • 还有一种方法:创建第三条指令 :)
  • @K.Toress :这非常有帮助。但现在我有一个问题。我想将项目传递给 之类的指令,但是在使用 $compile 使指令动态化后,我无法编写 var html = ' '+item.type+'>';在这种情况下它不起作用。
  • @K.Toress 我的意思是,如果我想从指令中显示模型的“名称”值,我不想从指令中访问整个数组。

标签: javascript angularjs angularjs-directive


【解决方案1】:

您为什么不尝试使用可以用作条件的范围数据的唯一指令:

<div ng-repeat="item in data">
  <directive data-env="item.type" data-name="item.name"></directive>
</div>

在指令中,您可以使用$scope.env 执行条件操作并仅显示您需要的内容。

【讨论】:

  • 实际上要求指令应该是独立的。我的意思是不同的开发人员会处理不同的指令,最后我们需要根据类型将所有指令集成到一个视图中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多