Javascript AngularJS:如何激活ngRepeat中的第一个非零项?
对于像这样的对象Javascript AngularJS:如何激活ngRepeat中的第一个非零项?,javascript,angularjs,Javascript,Angularjs,对于像这样的对象 notification: { "text":0, "image":2, "video":0 } 我看到一个ng repeat <div ng-repeat="items in notification"> // contents </div> //内容 如何将“活动”类分配给视图中的第一个非零通知类型? 附加 我知道一些在控制器或指令中处理它的方法。我正在寻找一种在视图内部处理它的方法 <div ng-repeat=
notification: {
"text":0,
"image":2,
"video":0
}
我看到一个ng repeat
<div ng-repeat="items in notification">
// contents
</div>
//内容
如何将“活动”类分配给视图中的第一个非零通知类型?
附加
我知道一些在控制器或指令中处理它的方法。我正在寻找一种在视图内部处理它的方法
<div ng-repeat="(name, value) in notification" ng-class="{'active': value && hasOneActive}" ng-init="hasOneActive = hasOneActive || value;">
// contents
</div>
//内容
编辑:感谢您检查该脚本,我已在本文中对其进行了更正,但新的解决方案看起来很复杂
<div ng-app="app" ng-controller="ctrl" ng-init="oldActive = false; newActive = false;">
<div ng-repeat="(k,v) in notification" ng-class="{'active': isActive}" ng-init="$parent.oldActive = $parent.newActive; $parent.newActive = !!($parent.newActive || v);
isActive = ($parent.newActive && !$parent.oldActive && ($index !== 0)) || ($parent.newActive && $index === 0)">
//contents
</div>
</div>
//内容
有自己的范围,所以我们不能简单地在中定义标志,并在找到第一个非零项时设置或清除它。但要解决这个问题,我们可以用诡计
因此,请参见下面的代码片段:
角度模块(“应用程序”,[])
.controller(“ctrl”,函数($scope){
$scope.notification={
“文本”:0,
"形象":二,,
"视频":1,,
“a”:0
};
});代码>
.active{
颜色:红色;
}
{{k}}:{{v}
ngRepeat的所有项中我只需要一个活动类,第一个无零项。这将为所有非零项添加。我已更正它,请移到,这似乎是真的,但正如您所说,此解决方案看起来很复杂:-)