ng 类指令调用执行两次

ng-class directive call executed twice

本文关键字:两次 执行 指令 调用 ng      更新时间:2023-09-26

Simple html:

<table class="table table-condensed">
 <tr data-ng-repeat="customer in customers" data-ng-class="customerSelectedClass(customer)">
  <td>
    <a href="" data-ng-click="selectCustomer(customer)">{{customer.Name}}</a>
  </td>
 </tr>
</table>

在我的控制器中 - 两个函数用于选择客户并返回正确的类以突出显示表行:

$scope.customerSelectedClass = function (customer) {
            if (customer == $scope.selectedCustomer) {
                console.log('returing info for ' + customer.Name);
                return "info";
            }
            return "";
        };
        $scope.selectCustomer = function (customer) {
            console.log('selecting ' + customer.Name);
            $scope.selectedCustomer = customer;
        }

我注意到,当我单击客户链接时,customerSelectedClass 函数会执行两次。 ng-click 指令上的 selectCustomer 函数执行一次,这是应该的。Angular 只在页面上包含一次。我想知道这是 Angular 中的错误还是我做错了什么?

在幕后,angular 正在解析类名的函数上设置一个$watch。 由于 angular 使用脏检查来查看是否有更改,因此在$digest周期中将调用此方法两次。 这没关系。

我建议您不要将此代码添加到控制器中,因为如果您要管理许多 css 类,您可能会添加大量不必要的代码。 请尝试以下操作:

<table class="table table-condensed">
 <tr data-ng-repeat="customer in customers" data-ng-class="{'info': customer == selectedCustomer}">
  <td>
    <a href="" data-ng-click="selectCustomer(customer)">{{customer.Name}}</a>
  </td>
 </tr>
</table>

然后,就不需要控制器功能customerSelectedClass。 仅当:的右侧解析为 true 时,这将添加info类。 并且在ng-repeat中解决正确的客户没有问题。

希望这有帮助。