Using ng-repeat angular with filter to exclude empty value
I am trying to get non-empty items in my selection with help filter
, but that doesn't work as expected.
<select ng-model="selectedSubject.id">
<option value="0">
<%= res.getString("portlet.form.subjectField.default") %>
</option>
<option ng-repeat="sujet in subjects.allSubjects | filter:{name_fr:'!!'}" value="{{sujet.id}}">
{{sujet.name_fr}}
</option>
</select>
+3
source to share
3 answers
filter:{my_field:'!!'}
will only filter out values null
.
If you want to filter out empty values, or both null
and empty, you must use a custom filter
<option ng-repeat="sujet in subjects.allSubjects | filter:notEmptyOrNull" value="{{sujet.id}}">{{sujet.name_fr}}</option>
controller
$scope.notEmptyOrNull = function(item){
return !(item.name_fr === null || item.name_fr.trim().length === 0)
}
+5
source to share
You have to set the model such that angular picks the right option base for ngModel selection
<select ng-model="selectedSubject.id" ng-options="sujet.id as sujet.name_fr in subjects.allSubjects track by sujet.id"></select>
And set the default id on the controller.
$scope.allSubjects = subjects;
$scope.selectedSubject.id = subjects[0].id;
0
source to share