对于像
这样的对象 notification: {
"text":0,
"image":2,
"video":0
}
我在视野中有ng-repeat
<div ng-repeat="items in notification">
// contents
</div>
如何分配“活跃”&#39;类到视图内的第一个非零通知类型?
其他
我知道一些在控制器或指令中处理它的方法。我正在寻找一种在视图中处理它的方法
答案 0 :(得分:1)
<div ng-repeat="(name, value) in notification" ng-class="{'active': value && hasOneActive}" ng-init="hasOneActive = hasOneActive || value;">
// contents
</div>
编辑:感谢Grundy检查该脚本,我已在此jsfiddle中对其进行了更正,但新解决方案看起来很复杂
<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>
答案 1 :(得分:0)
ngRepeat
有自己的范围,因此我们无法在ngInit
中简单地定义标记,并在找到第一个非零项目时设置或清除它。但是为了解决问题,我们可以使用$parent
property of Scope
请参阅下一段代码片段:
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.notification= {
"text":0,
"image":2,
"video":1,
"a":0
};
});
&#13;
.active{
color:red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl" ng-init="isFirst=true;">
<div ng-repeat="(k,v) in notification" ng-class="{active:isFirstActive }" ng-init="isFirstActive=$parent.isFirst&&v!=0;$parent.isFirst=$parent.isFirst&&v==0">
{{k}}:{{v}}
</div>
</div>
&#13;
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.notification= {
"text":0,
"image":2,
"video":1,
"a":0
};
});
&#13;
.active{
color:red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl" >
<div ng-repeat="(k,v) in notification" ng-class="{active:isFirstActive }" ng-init="isFirstActive=!$parent.isAcivated&&v!=0;$parent.isAcivated=$parent.isAcivated||v!=0">
{{k}}:{{v}}
</div>
</div>
&#13;