Reputation: 965
Is it possible to use ngMessages
to show an error while initializing options of a select
element using ngOptions
?
For ex. in
<select name="fruitNames" ng-model="fruitName" ng-options="fruit.name for fruit in fruits"></select>
if fruits
is empty, I want to show an error message.
Upvotes: 2
Views: 1158
Reputation: 123739
You could provide any expression to ng-messages
as a kvp, example i am setting boolean value to hasFruits
and using the key hasFruits
.
<div ng-messages="{noFruits:!fruits.length}" >
<div ng-message="noFruits">Sorry, No fruits available!!</div>
</div>
angular.module('app', ['ngMessages']).controller('ctrl', function($scope) {
$scope.fruits = [];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-messages.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div ng-messages="{hasFruits:!fruits.length}">
<div ng-message="hasFruits">No fruits available!!</div>
</div>
</div>
This however seems a bit weird since you really don't have multiple conditions here (Unlike the way you use ngMessages with $error object), you could just show and hide a div as well instead.
Upvotes: 5