This particular question pertains to a topic that was previously discussed in another thread
The scenario involves using a ng-repeat
as shown below:
<li ng-repeat="opt in namesCtrl.uniqueCars">
<input type="checkbox" ng-model="namesCtrl.filter['cars'][opt.element]" | orderBy:['checkbox','-count']"><p2>{{opt.element}} ({{opt.count}})</p2>
</li>
In this setup, the elements are derived from this.uniqueCars
this.uniqueCars=[
{'element':'Ford','count':3,'checkbox':false},
{'element':'Honda','count':2,'checkbox':false},
{'element':'Ferrari','count':1,'checkbox':false},
{'element':'Delorean','count':6,'checkbox':false}
];
Checked items on the display list are then sent to this.filter
for a separate purpose
this.filter = {
"cars": {}
}
The main objective here is to sort the checkbox list visible in the view so that when an item is checked, it moves to the top of the list. The intended result should resemble something like this
To achieve this, there is a $watch
implemented in the following manner:
$scope.$watch("namesCtrl.filter", function(nv,ov){
angular.forEach(self.uniqueCars, function(opt){
opt.checkbox = nv.cars[opt.element]
})
}, true)
However, the behavior observed during sorting based on the checkbox value is inconsistent. When initially clicked, it works fine, but upon unclicking, the sorting does not work properly. Clicking again results in reverse ordering.
Hence, the aim is to refine this functionality by modifying the existing $watch
. This approach is chosen because real-life scenarios may involve modifications to this.filter
by other elements, necessitating constant monitoring of changes.
Note: the addition of the this.uniqueCars.checkbox
field is done intentionally to enable proper sorting and can be adjusted accordingly.
You can access a functional example on Plunker here.