How to order checked checkbox at the top of the list in AngularJS

I am consuming data from api and display it in the normal list view along with checkbox.There are two api where I have full list of resource in one and selected resource in another.

Currently like this

enter image description here

Expected list would be

enter image description here

here is my checkbox in ng-repeat loop

<div class="search" ng-repeat="resource in ViewData.resources">
    <input type="checkbox" value="{{resource.resourceName}}" ng-model="resourceList[resource.resourceId]" 
                            ng-click="resourceChange(resource.resourceId)"
                            ng-checked="checkSelectedResource(resource.resourceId)"> 
    <label class="list{{resource.resourceId}}" >{{resource.resourceName}}</label>
</div>

Upvotes: 0

Views: 2423

Answers (3)

krutkowski86
krutkowski86

Reputation: 1083

Here's a working example: http://jsfiddle.net/irhabi/fqdqbpbc/

HTML

<div ng-controller="MyCtrl">
  <div class="search" ng-repeat="fruit in fruits | orderBy:['-checked','name']:false">
    <input id="fruit{{$index}}" type="checkbox" ng-model="fruit.checked"> 
      <label for="fruit{{$index}}">{{fruit.name}}</label>
   </div>
   <br/>
   <p>fruits model:</p>
   <pre>{{fruits|json}}</pre>
</div>

JS

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', MyCtrl);

function MyCtrl($scope) {
    $scope.fruits = [
      {name:'apple',checked:false},
      {name:'banana',checked:false},
      {name:'orange',checked:false}
    ];
}

Upvotes: 1

Majid
Majid

Reputation: 2900

change your code to this

<div class="search" ng-repeat="resource in ViewData.resources">
    <input type="checkbox" value="{{resource.resourceName}}" ng-model="resourceList[resource.resourceId]" 
                            ng-click="resourceChange(resource.resourceId)"
                            ng-checked="$first"> 
    <label class="list{{resource.resourceId}}" >{{resource.resourceName}}</label>
</div>

you can easily trigger click event of first element in Controller like

   $scope.checkFirst=function(first){if(first == true){ //your function }}

and if you want to order for instance by name do this

 ng-repeat="resource in ViewData.resources | orderBy://name for example

Upvotes: 0

G&#252;rsel
G&#252;rsel

Reputation: 135

you can control with ng-if. if ng-checked items are true, you can use ng-show="$first"

Upvotes: 1

Related Questions