javascript - 根据范围值添加指令

标签 javascript angularjs angularjs-directive

我在 Controller 的范围内有一个数组,例如

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

现在,在 View 中,我正在对模型数据执行循环,并且我有两个指令,一个是测试,另一个是生产。我想根据类型在 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}}>

但显然它不起作用。

最佳答案

为什么不尝试使用一个唯一的指令,其中包含可以用作条件的范围数据:

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

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

关于javascript - 根据范围值添加指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31099917/

相关文章:

javascript - 在多级 Mongoose 模式中设置属性

javascript - 如何正确导出和处理可编辑表格中的数据

javascript - Tornado :包含缩小的 javascript 的 UIModule

javascript - jQuery Ajax 调用执行多次 - Chrome 浏览器

javascript - 从 Google API RSS Feed 加载更多内容

javascript - 使用 {{index+1}} angularjs 更改参数

javascript - Angular : select ng-model programmatically changed but ng-change event doesn't fire

javascript - 未知提供者 : $animateCssProvider <- $animateCss <- $uibModalStack <- $uibModal

angularjs - Angular2 - 指令选择器上的 ngclass

javascript - 如何正确使用 ng-cloak 指令?