在 Angular 中的两个按钮之间切换 class 但进行限制以防止更改同一按钮 class

Toggle class between two buttons in Angular but restrict to prevent same button from changing class

尝试创建一些非常基本的功能,基本上使两个按钮的行为类似于单选按钮。有两个按钮,用于根据显示的内容 show/hide 不同的内容。所以它按预期工作,除了它在任何点击时都会发生变化。因此,如果我单击同一个按钮两次,它就会更改 class。如果单击另一个按钮,我只需要更改它:

<button class="someClass" ng-class="{true: 'green', false: 'blue'}        [!yupNope.isSelected]" ng-click="yupNope.isSelected = !yupNope.isSelected">YES</button>
   <button class="someClass" ng-class="{false: 'green', true: 'yupNope'}[!yupNope.isSelected]" ng-click="yupNope.isSelected = !yupNope.isSelected">NO</button>

因此,如果单击“是”,则它应该更新,“否”也应该更新。但是,如果在单击“否”之前再次单击“是”,则应该没有任何变化。

这是一个可以玩的 Plunkr:

Plunkr Demo

ng-click 表达式添加条件:

<button class="someClass" ng-class="{true: 'green', false: 'blue'}[!yupNope.isSelected]" 
  ng-click="yupNope.isSelected ? (yupNope.isSelected = !yupNope.isSelected) : ''">YES</button>
 <button class="someClass" ng-class="{false: 'green', true: 'yupNope'}[!yupNope.isSelected]" 
  ng-click="!yupNope.isSelected ? (yupNope.isSelected = !yupNope.isSelected) : ''">NO</button>

你修改后的plunkr.

而不是 yupNope.isSelected = !yupNope.isSelected 作为 ngClick 表达式分别将 yupNope.isSelected 设置为 true/false:

<button ng-click="yupNope.isSelected = false" class="someClass" ng-class="{true: 'green', false: 'blue'}[!yupNope.isSelected]">YES</button>
<button ng-click="yupNope.isSelected = true" class="someClass" ng-class="{false: 'green', true: 'yupNope'}[!yupNope.isSelected]">NO</button>

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

您可以使用 ng-disabled 来完成此操作。您可以在每个按钮上应用 ng-disabled 属性。

<button class="someClass"
    ng-class="{true: 'green', false: 'blue'}[!yupNope.isSelected]" 
    ng-click="yupNope.isSelected = !yupNope.isSelected"
    ng-disabled="yupNope">YES</button>

<button class="someClass"
    ng-class="{false: 'green', true: 'yupNope'}[!yupNope.isSelected]"
    ng-click="yupNope.isSelected = !yupNope.isSelected"
    ng-disabled="!yupNope">NO</button>

您可以在此处找到文档: https://docs.angularjs.org/api/ng/directive/ngDisabled