基于动态数据的ng-repeat中用于不同AngularJS指令的模式

wis*_*nIV 6 angularjs angularjs-directive

我正在从一组数据动态构建仪表板.仪表是D3.

我在AngularJS指令中定义了一系列不同的D3测量仪.在我的页面上,我有一个ng-repeat迭代度量数组.

我的问题是什么是基于ng-repeat数组中的数据属性动态选择正确指令的最佳方法?

有没有办法创建一个工厂模式,其中使用的指令是基于数组的输入值?或者是否有办法通过动态地在指令中包含其他指令来仅使用指令来实现结果?

HTML

<div ng-controller="DashboardCtrl">
<div id="oppChart">
    <div>
        <gh-visualization ng-repeat="item in metrics" val="item[0]"></gh-visualization>
    </div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)

度量数组(将是动态的):

$scope.list = [
        { 'title': 'XYX','data-type':'', 'query':'SELECT ...' },
        { 'title': 'Revenue', 'data-type':'', 'query':'SELECT ...'  }
      ];
Run Code Online (Sandbox Code Playgroud)

D3指令基于此 - http://briantford.com/blog/angular-d3.html

Mik*_*son 6

那就是 ng-switch

<div ng-repeat="item in metrics">
  <div ng-switch on="item.type">
    <div ng-switch-when="optionA">..include </div>
    <div ng-switch-when="optionA">..include </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)


Sta*_*fen 0

你的第二个解决方案听起来更有角度。因此,如果它只是动态添加的单个指令

app.directive('dynamically',function(){ 
  return {
    restrict: 'A',
    compile: function(element,attrs){
      var directives = [];
      if (attrs.dynamically.indexOf(' ') > -1){
        directives = attrs.dynamically.split(' ')
      } else {
        directives.push(attrs.dynamically)
      };
      var html = '<ANY ';
      for (var i in directives){
        html += directives[i] + '="true" ';
      };
      html += '></ANY>';
      element.replaceWith(html)
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

这是一种方法。

1)if (attrs.dynamically.indexOf(' ')以便您可以在一个实例中实现多个指令,在本示例中用空格字符 (' ') 分隔。

2)我通过询问将 '="true"' 添加到我使用的属性中if (attrs.x) {...},如果属性 x 没有值,即使在 DOM 上声明并位于该值,它也不存在。