Search code examples
javascriptangularjsng-options

Array Changing to String When Updating Value


I have a list on my HTML page. This list pulls from an array using ng-options. One of the object array's properties is show. The ng-options uses a filter to only display options where show == 1. When the user hits a button the select item in the list is added to an array and the show value needs to be set to 0 so it is removed from the list. The value is being set to 0 but the ng-options is now printing the options for the select incorrectly.

Array Definition

referenceTypes: Array<any> = [
            { label: 'Customer Reference', show: 1 },
            { label: 'PO Number', show: 1 },
            { label: 'SO Number', show: 1 }
        ]

Button Click

addReferenceType = () => {
            ... 

            // hide the reference type from the add drop down list
            this.referenceTypes.filter(option => option.label == this.referenceType)[0].show = 0;
        }

HTML

<select ng-model='$ctrl.referenceType'
        ng-options="option.label as option.label for option in $ctrl.referenceTypes | filter: {show: 1}">
    <option value=""></option>
</select>

Before

Before

After

After


Solution

  • you need to change your code in this way, otherwise one time the filter returns an empty array and you have that error, because the click is triggered twice.

    addReferenceType() { 
        let filteredTypes: Array<any> = 
        this.referenceTypes.filter(option => option.label == this.referenceType); 
        if (filteredTypes.length > 0) { 
            filteredTypes[0].show = 0; 
        } 
     }