Search code examples
angularjshtml-selectng-options

How to use ng-options to set the same text no matter the option selected - Angular.js


I understand how to set the default value of the options box.

My question is different in that there is a default value "Actions" - and there are 3 other filtering options that can be selected...

    $scope.actions = [
		{display_name:"Actions", type:"unknown", box_display: "Actions"},
		{display_name:"Mark all incoming voicemails as read", type:"read", box_display: "Actions"},
		{display_name:"Mark all incoming voicemails as unread", type:"unread", box_display: "Actions"},
		{display_name:"Delete all read incoming voicemails", type:"delete", box_display: "Actions"},
    ];
$scope.selectedAction = $scope.actions[0];
<select class="XButton XButtonNormal XButtonDropDown disabled-false" ng-model="selectedAction"
            ng-options = "action_option.display_name for action_option in actions"
            ng-change="handleVoiceMailAction(selectedAction.type)"
        >
            <option>Actions</option>

How do I get the selection box to display "Actions" no matter which of the 4 objects in the array is selected. The different options still need to be visible when selecting the options (and the functionality needs to correspond to the appropriate selection), but I want the box to continue to display "Actions" after a selection is made.


Solution

  • This does what you look for :

    Template :

    <select ng-model="selectedAction" ng-options="action.display_name for action in actions" 
                                      ng-change="setCurrentAction(selectedAction)"></select>
    <p>Current action : {{currentAction}}</p>
    

    Controller :

    $scope.actions = [{
        display_name: "Actions",
        type: "unknown"
    }, {
        display_name: "Mark all incoming voicemails as read",
        type: "read"
    }, {
        display_name: "Mark all incoming voicemails as unread",
        type: "unread"
    }, {
        display_name: "Delete all read incoming voicemails",
        type: "delete"
    }];
    
    $scope.selectedAction = $scope.currentAction = $scope.actions[0];
    
    $scope.setCurrentAction = function (action) {
        $scope.currentAction = action;
        $scope.selectedAction = $scope.actions[0];
    };
    

    See fiddle

    Explanation:

    As you want to display 'Action' for the action binded to the ng-model attribute of the dropdown, we have to make the distinction between the selectedAction from the dropdown point of view, and the selected action for your application logic. I called that latter action the currentAction. On a selection event, we have to register the selected action to the current action.