Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 编写AngularJS指令以从数组生成表的正确方法_Javascript_Angularjs_Angularjs Directive - Fatal编程技术网

Javascript 编写AngularJS指令以从数组生成表的正确方法

Javascript 编写AngularJS指令以从数组生成表的正确方法,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我想创建一个指令,该指令从数组生成一个完整的表,提供特定的onMouseOver行为,当单击一个单元格时,强调具有相同值的所有单元格(以及本例中不重要的其他特定行为) 在这种方法中,仍然存在一个问题,因为addClass调用似乎适用于元素,因为它在添加tr/td元素之前是 (3)ng重复并在每个tr/th/td元件上使用指令 这是一种我没有测试过的方法,因为我有20多个表要显示,HTML文件中的表代码越短越好 所以问题是:正确的方法是什么?或者可能没有一个是正确的,这样的问题应该用另一种方法来解

我想创建一个指令,该指令从数组生成一个完整的表,提供特定的onMouseOver行为,当单击一个单元格时,强调具有相同值的所有单元格(以及本例中不重要的其他特定行为)

在这种方法中,仍然存在一个问题,因为
addClass
调用似乎适用于元素,因为它在添加tr/td元素之前是

(3)
ng重复
并在每个tr/th/td元件上使用指令
这是一种我没有测试过的方法,因为我有20多个表要显示,HTML文件中的表代码越短越好


所以问题是:正确的方法是什么?或者可能没有一个是正确的,这样的问题应该用另一种方法来解决?

我相信你的方法1是正确的。我建议在本指令中添加一个控制器,其功能由
ng click
ng mouseover
触发,而不是尝试在link函数中实现所需的功能:

controller: ['$scope', function MyTableController($scope) {
  $scope.doSomething = function() {
    // your code here
  };

  $scope.highlightSameValues = function(cell) {
    // your code here
  };
}];
因此,例如,如果您希望在鼠标悬停并单击每个单元格时发生某些“事情”,请将
td
更改为以下内容:

<td
  class="centered"
  ng-repeat="cell in row track by $index"
  ng-mouseover="doSomething()"
  ng-click="highlightSameValues(cell)">
  {{cell}}
</td>

{{cell}}
app.directive('myTableDirective', function() {
    return {
        restrict: 'E',
        replace: false,
        scope: {
            values: '='
        },
        link: function(scope, elem, attrs)
        {
            scope.$watch( 'tableData', function(val)
            {
                if( val ) {
                    var row;
                    for( var t=0; t<val.values.length; t++ ) {
                        row = angular.element('<tr></tr>');
                        for( var f=0; f<val.values[t].length; f++ ) {
                            row.append( '<td>' + val.values[t][f] + '</td>');
                        }
                        elem.append( row );
                    }
                }
                elem.addClass('my-table-css-class');
            }
        }
    };
});
controller: ['$scope', function MyTableController($scope) {
  $scope.doSomething = function() {
    // your code here
  };

  $scope.highlightSameValues = function(cell) {
    // your code here
  };
}];
<td
  class="centered"
  ng-repeat="cell in row track by $index"
  ng-mouseover="doSomething()"
  ng-click="highlightSameValues(cell)">
  {{cell}}
</td>