假设你有一个在ul中呈现的数组,每个元素都有一个li,控制器上有一个名为selectedIndex的属性。在AngularJS中,用索引selectedIndex向li中添加类的最好方法是什么?

我目前复制(手工)li代码,并将类添加到li标记之一,并使用ng-show和ng-hide只显示每个索引一个li。


当前回答

如果你想超越二进制计算,让你的CSS远离你的控制器,你可以实现一个简单的过滤器,根据map对象计算输入:

angular.module('myApp.filters, [])
  .filter('switch', function () { 
      return function (input, map) {
          return map[input] || '';
      }; 
  });

这允许你像这样写你的标记:

<div ng-class="muppets.star|switch:{'Kermit':'green', 'Miss Piggy': 'pink', 'Animal': 'loud'}">
    ...
</div>

其他回答

我最近做的是这样的:

<input type="password"  placeholder="Enter your password"
ng-class="{true: 'form-control isActive', false: 'isNotActive'}[isShowing]">

isshows值是位于我的控制器上的值,可以通过单击按钮进行切换,单括号之间的部分是我在css文件中创建的类。

编辑:我还想补充一点,codeschool.com有一个免费的课程,由谷歌赞助,在AngularJS上,涵盖了所有这些东西。不需要支付任何东西,只是注册一个帐户,然后开始! 祝大家好运!

只是添加了一些对我来说有用的东西,经过大量的搜索……

<div class="form-group" ng-class="{true: 'has-error'}[ctrl.submitted && myForm.myField.$error.required]">

希望这有助于您的成功开发。

=)

无文档的表达式语法:伟大的网站链接…=)

我理解这个问题是针对angular的,但如果有人在使用React或基于React的框架(Amplify、NextJS、Serverless等),解决方案就简单多了。最有效的方法是使用这样的三元运算符:

<div className={condition ? "classnameiftrue" : "classnameiffalse"}>

如果使用useState(),您可以使用此策略来动画树,因为每次状态改变时,它都会用新值重新加载该条件。

检查这个。

臭名昭著的AngularJS if|else语句!! 当我开始使用Angularjs时,我有点惊讶地发现我找不到if/else语句。

所以我在一个项目上工作,我注意到当使用if/else语句时,条件显示在加载时。 您可以使用ng-cloak来修复这个问题。

<div class="ng-cloak">
 <p ng-show="statement">Show this line</span>
 <p ng-hide="statement">Show this line instead</span>
</div>

.ng-斗篷{显示:none}

由于火绒

这里有一个更简单的解决方案:

function MyControl($scope){ $scope.values = ["a","b","c","d","e","f"]; $scope.selectedIndex = -1; $scope.toggleSelect = function(ind){ if( ind === $scope.selectedIndex ){ $scope.selectedIndex = -1; } else{ $scope.selectedIndex = ind; } } $scope.getClass = function(ind){ if( ind === $scope.selectedIndex ){ return "selected"; } else{ return ""; } } $scope.getButtonLabel = function(ind){ if( ind === $scope.selectedIndex ){ return "Deselect"; } else{ return "Select"; } } } .selected { color:red; } <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script> <div ng-app ng-controller="MyControl"> <ul> <li ng-class="getClass($index)" ng-repeat="value in values" >{{value}} <button ng-click="toggleSelect($index)">{{getButtonLabel($index)}}</button></li> </ul> <p>Selected: {{selectedIndex}}</p> </div>