Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can ngOptions call a function to get display text?

I have a select tag that I'm binding to an array of radio station objects using AngularJS. My object has the following properties:

{
    id: 'WXYZ',
    name: 'Radio Station Name (optional)',
    frequency: '89.7 FM'
}

I'd like each element in the dropdown to show "{id} - {name} - {frequency}" as the display text, but since the name property is optional, I'd like to avoid double dashes in the event that an object has no value for its name.

I was able to get this working:

<select ng-model="StationPreference" ng-options="s.id+ ' - ' + s.name + ' - ' + s.frequency for s in stations">
    <option value="">-- select --</option>
</select>

What are the rules/guidelines/best practices for calling a function inside ng-options? I'd like to do something like getDisplayText(s) -- what makes the expression "valid for angular"? does the function have to be defined inside the scope? Can it be any externally defined function? Is this the best approach for the desired functionality?

like image 322
Brian Oliver Avatar asked Feb 14 '14 16:02

Brian Oliver


People also ask

How does ng-options work as?

Definition and Usage. The ng-options directive fills a <select> element with <options>. The ng-options directive uses an array to fill the dropdown list. In many cases it would be easier to use the ng-repeat directive, but you have more flexibility when using the ng-options directive.

What is ngOptions?

The ngOptions attribute can be used to dynamically generate a list of <option> elements for the <select> element using the array or object obtained by evaluating the ngOptions comprehension expression.

How do I filter with Ng-options?

In AngularJS when you are using ng-options, you can filter out the options by calling a custom function you have in the controller. Let's say you have following set of employees and when you display all these employees inside HTML select using ng-options, you can see all the employees in a dropdown.

How do I set default selected value in ng-options?

In my opinion the correct way to set a default value is to simply pre-fill your ng-model property with the value selected from your ng-options , angular does the rest. Essentially when you define the $scope property your select will bind to assign it the default value from your data array.


1 Answers

this worked for me:

<select ng-model="myForm.car"
        ng-options="obj.id as genName(obj.id,obj.name) for obj in myForm.options">
    <option value="">Select...</option>
</select>


$scope.myForm.options = [
    { id : "nissan", name: "Nissan" },
    { id : "toyota", name: "Toyota" },
    { id : "fiat"  , name: "Fiat" }
];

$scope.genName = function(id,name) {
    return id + ' ' + name;
}
like image 75
koolunix Avatar answered Oct 06 '22 23:10

koolunix