AngularJS: how to activate the first non-null element in ngRepeat?

For an object of type

 notification:  {
  "text":0,
  "image":2,
  "video":0
 }

      

I have ng-repeat

in view

<div ng-repeat="items in notification">
  // contents
</div>

      

how to assign the "active" class to the first non-null notification type inside the view?
additional
I know some approaches to handling it in controllers or directives. I am looking for a way to handle it inside a view

+3


source to share


2 answers


ngRepeat

have their own scope, so we cannot simply define a flag in ngInit

and set or clear it when the first non-null element was found. But for the solution, we can use the trick with the property $parent

Scope

See the following code snippets:

angular.module("app",[])
.controller("ctrl",function($scope){
    $scope.notification= {
        "text":0,
        "image":2,
        "video":1,
        "a":0
    };
});
      

.active{
    color:red;
}
      

<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>
      

Run codeHide result




angular.module("app",[])
.controller("ctrl",function($scope){
    $scope.notification= {
        "text":0,
        "image":2,
        "video":1,
        "a":0
    };
});
      

.active{
    color:red;
}
      

<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>
      

Run codeHide result


0


source


<div ng-repeat="(name, value) in notification" ng-class="{'active': value && hasOneActive}" ng-init="hasOneActive = hasOneActive || value;">
  // contents
</div>

      

EDIT: Thanks to Grundy for the script, I fixed it in this jsfiddle , but the new solution looks complicated



<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


source







All Articles