简体   繁体   中英

Conditionally change value of ng-model for input

I have following HTML code:

<input type="text" ng-model="search.isOrdered"/>

If user types ordered word to input then I want ng-model = true , if user types unordered word to input, then I want ng-model = false . In other cases I want to ng-model = undefined or ng-model = null . Suppose I can't use radio-button or checkbox.

How to achieve this?

Thanks

Use ng-change instead:

<input type="text" ng-model="search.order" ng-change="search.isOrdered = search.order == 'ordered'"/>

See working fiddle

Change your HTML as follows:

<input type="text" ng-model="search.isOrderedInput"/>

In your controller:

    $scope.isOrdered = function() {
        var isOrdered;

        switch ($scope.isOrderedInput) {
        case 'ordered':
            isOrdered = true;
            break;
        case 'unordered':
            isOrdered = false;
            break;
        default:
            isOrdered = undefined;
            break;

        }

        return isOrdered;
    };

This should be more maintainable than adding logic to the view via ng-change, no?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM