【问题标题】:Angular toggling variable within ng-click not workingng-click 中的角度切换变量不起作用
【发布时间】:2014-12-11 23:06:09
【问题描述】:

我有一个列出客户的表格,对于也有客户列表的客户,允许用户单击表格行以显示该列表。 HTML 如下所示:

        <tbody ng-repeat ="item in customers | clientSettingsFilter:customerId">
            <tr ng-class="{'row-hover': item.clientSettings.length>0}" ng-click="item.showClients=!item.showClients">
                <td><span ng-class="{true:'glyphicon glyphicon-chevron-down', false:'glyphicon glyphicon-chevron-right'}[item.showClients]"  ng-hide="item.clientSettings.length==0"></span></td>
                <td>{{item.id}}</td>
                <td>{{item.name}}</td>
                <td><button type="button" class="btn btn-default btn-xs" ng-click="go('/client-config/defaults/'+item.id)">Defaults</button></td>
            </tr>
            <tr ng-show="item.showClients">
                 ..... // client data

我的奇怪行为是这样的:

如果我在客户数据集中未定义“showClients”属性,一切都会按预期工作,除了 V 形图标一开始没有显示。单击一次后,它会显示并且切换按预期工作。我在想这可能是因为 ng-class 正在寻找 true 或 false,而 undefined 不满足其中任何一个。

如果我将 showClients 属性预定义为 true 或 false,则 V 形在页面加载时正确显示并且客户端列表正确显示,但切换不再起作用,就好像 ng-click 没有做任何事情或某些原因无法更改该值。我不确定如何调试这样的内联指令。

编辑

根据请求,这是来自控制器的相关代码:

filter('clientSettingsFilter', function () {
    return function (customers, customerId) {
        var filtered = [];

        if (!customerId)
            return filtered;

        customerId = customerId.toLowerCase();

        angular.forEach(customers, function (item) {
            if (item.id.toLowerCase().indexOf(customerId) !== -1) {

                // format some text properties, omitted for brevity

                // if this line is uncommented, the ng-click does not work
                //item.showClients = false;
                filtered.push(item);
            }
        });

        return filtered;
    };
});

【问题讨论】:

  • 请加你的js代码
  • @Floradu88 已编辑。控制器中唯一发生的事情是我是否设置了 showClients 属性。
  • 能否请您给我们一个详细的客户对象以更好地了解流程?

标签: angularjs angularjs-directive


【解决方案1】:

您在ng-class 中使用的条件只会在值为truefalse 时添加内容,而不是在undefined 时添加内容。

改为使用更冗长的三元运算符:

ng-class="item.showClients ? 'glyphicon-chevron-down' : 'glyphicon-chevron-right'"

还不如将glyphicon类移到普通的class属性:

class="glyphicon"

演示: http://plnkr.co/edit/bxgp4HyFkOygc0foxAKN?p=preview

您在过滤器中取消注释 item.showClients = false; 时看到的行为是由于摘要循环的工作方式。

如果item.showClientsfalse 并且您单击tr 将发生以下情况(有点简化):

  1. ng-click 中的表达式将执行,将item.showClients 设置为true
  2. 摘要循环将开始
  3. 过滤器将运行并再次将item.showClients 设置为false

过滤器是用来过滤的,不是用来修改的。

还请注意,当使用带有ng-repeat 的过滤器时,它会触发每个摘要循环,并且由于每个摘要循环由多个摘要循环(至少两个)组成,因此保持过滤器简单很重要,否则它们会对性能。

【讨论】:

  • 无法产生ng-click 不起作用的场景。
  • 好的,我明白了。但 showClients 仍然未定义。观察在列表中定义它时会发生什么:plnkr.co/edit/J59fLIa3wggKPj6v58U5?p=preview(我只更改了第 29 行,item.showClients = false,如果您将其注释掉,它会再次起作用)
  • 啊,这很有道理。因此,如果我想处理任何数据,或者例如为某些客户将 showClients 的初始状态设置为 true,我应该在实际查询的结果函数中的控制器中执行此操作,而不是在过滤器中,对吗?
猜你喜欢
  • 1970-01-01
  • 2017-05-12
  • 1970-01-01
  • 2017-04-04
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 2016-11-24
相关资源
最近更新 更多