Angular

In salesforce.com Visualforce pages the default option value for null is not being displayed. I have a very simple select component with one option child for the none or null value as defined by the Angular Docs (http://docs.angularjs.org/api/ng/directive/select).

Here is the app:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"/>
<script>
    var myApp = angular.module('myApp',[]);

    function MyCtrl($scope) {
        $scope.colors = [
            {name:'black', shade:'dark'},
            {name:'white', shade:'light'},
            {name:'red', shade:'dark'},
            {name:'blue', shade:'dark'},
            {name:'yellow', shade:'light'}
        ];
    }
</script>

<div ng-app="myApp">
    <div ng-controller="MyCtrl">
        <select ng-model="color" ng-options="c.name for c in colors">
            <option value="">-- choose color --</option>
        </select>   
        {{color.name}}
    </div>
</div>

As you can see on this page, http://geopointedev-developer-edition.na14.force.com/angularoption , the “– choose color –” option is not displayed. But on this jsfiddle, http://jsfiddle.net/MTfRD/670/ , it is working perfectly. Any ideas why the none option is not being displayed in salesforce.com Visualforce pages?

Answer

Tehnrd,

Long story short:

ng-options validates the Options list it generates against the evaluated scope statement given to it.

From your source above, ‘–choose color–‘ isn’t part of the $color array. While the docs specifically mention using a option element with an nil value for the “nothing selected” element, I’ve discovered that visualforce strips the options tags that have a nil value. If you look at your visualforce rendered source, the nil value option element is missing. Because the element is missing, ng-option is inserting a blank select option.

Two ideas for a direct workaround

1: Given a select object with id “colorSelect”:

angular.getElement('#colorSelect').append('<option value=\'\'>--choose color--</option>');

before your ng-options directive is executed. thats ugly and hacky and i don’t like it. Likewise you could alter the value, if you chose that way. Thats actually probably a better way.

2: I think the most-elegant way to do this (and it’s still lipstick on a pig) is to add your ‘–choose color–‘ option to the $scope.colors array as a value. Ng-options will render it as the selected option once you set $scope.color = ‘–choose color–‘

Then create a watch function that removes ‘–choose color–‘ from the array when $scope.color changes.

Here’s a js Fiddle with the watch statement doing it’s job and the default being chosen from teh given array.

http://jsfiddle.net/Nr9L4/

Attribution
Source : Link , Question Author : TehNrd , Answer Author : metadaddy

Leave a Comment