首页 文章

自定义指令上的对象数组的重复次数不起作用

提问于
浏览
2

我试图在下面的对象的数组上使用ng-repeat来重复我的自定义指令 .

我的数组看起来像下面 .

var Competitors = [];
Competitors.push({
  key: 1,
  value: {}//Blank object
});
Competitors.push({
  key: 2,
  value: {}//Blank object
});
Competitors.push({
  key: 3,
  value: {}//Blank object
});

我的自定义指令 .

module.directive('miChart', function () {

        return {
            restrict: 'E',
            template: '<div></div>',
            scope: {
                chartData: "=value",
                chartObj: "=?"
            },            
            replace: true,
            link: function ($scope, $element, $attrs) {
                $scope.$watch('chartData', function (value) {
                    if (!value) {
                        return;
                    }

                    $scope.chartData.chart.renderTo = $scope.chartData.chart.renderTo || $element[0];
                    $scope.chartObj = new Highcharts.Chart($scope.chartData);
                });
            }
        }
    });

这是我试图用我的指令创建多个图表的代码 .

<div ng-repeat="(key,value) in Competitors">
  <mi-chart value="Competitors[key]" chart-obj="Competitors[key]"></mi-chart>
</div>

当我调试我的代码时,该指令没有得到确切的值,并将竞争对手[key]作为值和chart-obj给出 . 所以它不会取代ng-repeat上的值 .

任何人都能说出我在做什么,这个问题的解决方案是什么 .

1 回答

  • 0

    我修改你的html像这样:

    <div ng-repeat="competitor in Competitors track by competitor.key">
       <mi-chart value="competitor" chart-obj="competitor"></mi-chart>
    </div>
    

    这会导致元素的正确绑定,如下面的代码片段所示 .
    逐个组件的轨道是可选的,但由于您已经拥有唯一的键值,因此使用它是明智之举 . 它可以在某些条目更新时提高性能 .

    但是我不确定这是不是你想要的 .

    var module = angular.module('app',[]);
    
    module.controller('ctrl', function($scope){
      $scope.Competitors = [];
      $scope.Competitors.push({
        key: 1,
        value: {}//Blank object
      });
      $scope.Competitors.push({
        key: 2,
        value: {}//Blank object
      });
      $scope.Competitors.push({
        key: 3,
        value: {}//Blank object
      });
    });
    module.directive('miChart', function () {
            
            return {
                restrict: 'E',
                template: '<div>-----------
    chartData - key: {{chartData.key}} value: {{chartData.value}}
    chartObj - key: {{chartObj.key}} value: {{chartObj.value}}</div>', scope: { chartData: "=value", chartObj: "=?" }, replace: true, link: function ($scope, $element, $attrs) { $scope.$watch('chartData', function (value) { if (!value) { return; } //$scope.chartData.chart.renderTo = $scope.chartData.chart.renderTo || $element[0]; //$scope.chartObj = new Highcharts.Chart($scope.chartData); }); } } });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="app" ng-controller="ctrl">
      Entries:
      <div ng-repeat="competitor in Competitors track by competitor.key">
        <mi-chart value="competitor" chart-obj="competitor"></mi-chart>
      </div>
    </div>
    

相关问题