AngularJS -表中的指令一行接一行

AngularJS - Directive row by row in a table

本文关键字:一行 指令 AngularJS      更新时间:2023-09-26

我有一个通过PHP生成的表格,同时由AngularJS处理:

<table>
   <tr>
     <th>Col 1</th>
     <th>Col 2</th>
     <th>Col 3</th>
   </tr>

   <?php
      while(...){
   ?>
       <tr>
          <td>
             <input type="text" ng-model="calcolo.ore">
          </td>
          <td>
             <input type="text" ng-model="calcolo.ricavo">
          </td>
          <td>
             <input type="text" ng-model="calcolo.abbatt">
          </td>
          <td>
             <input type='text'  ng-show="calcolo.abbatt" value='{{netti() | currency:"&euro;"}}'>
          </td>
       </tr>
   <?php } ?>

angular.module("myApp", ['ng-currency'])
    .controller("userController",
        function($scope) {
             $scope.fattlord = function() {
                return ($scope.calcolo.ore * $scope.calcolo.ricavo)
            };

            $scope.netti = function() {
                return ($scope.calcolo.ricavo-(($scope.calcolo.abbatt * $scope.calcolo.ricavo)/100))
            };

        });

当然,当我写入一个文本输入时,所有具有相同ng-model的输入都会得到相同的值。

有没有一种方法在Angular中,也许有id,允许我逐行编译,而不改变其他人?

不好意思,英语不好,谢谢!

PS:我不能使用ng-repeat

您可以为calcolo使用数组,并在PHP中增加每一行的索引:ng-model="calcolo[0].abbatt", ng-model="calcolo[1].abbatt"

然后在你的控制器中你可以循环遍历calcolo数组。

正如@yBrodsky在评论中提到的,在每个<tr>上使用控制器,因此您可以为每个<tr>具有不同的作用域。

<script data-require="angular.js.1.3@*" data-semver="1.5.2" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.2/angular.js"</script>
<body data-ng-app="myApp">
<table>
    <tr>
        <th>Col 1</th>
        <th>Col 2</th>
        <th>Col 3</th>
    </tr>
    <?php
      $i = 0;
      while($i++ < 5){
    ?>
    <tr data-ng-controller="userController">
        <td>
            <input type="text" ng-model="calcolo.ore">
        </td>
        <td>
            <input type="text" ng-model="calcolo.ricavo">
        </td>
        <td>
            <input type="text" ng-model="calcolo.abbatt">
        </td>
        <td>
            <input type='text'  ng-show="calcolo.abbatt" value='{{netti() | currency:"&euro;"}}'>
        </td>
    </tr>
    <?php } ?>
</table>
<script>
    angular.module("myApp", [])
    .controller("userController",
        function($scope) {
            $scope.calcolo = {}; //init
            $scope.fattlord = function() {
                return ($scope.calcolo.ore * $scope.calcolo.ricavo)
            };
            $scope.netti = function() {
                return ($scope.calcolo.ricavo-(($scope.calcolo.abbatt * $scope.calcolo.ricavo)/100))
            };
        }
       );
</script>
</body>