简体   繁体   中英

How to get the value of a html select in AngularJS after using a filter in the ng-options expression

I used a filter in my ng-options expression to convert all the options to uppercase but now when I want to get the value that the user selected I get a undefined

here is my select

<select name="selectThings" class="form-control"  
                                    id="selectThings" 
                                    ng-model="selectThings"

                                    ng-options="thing.name as (thing.name | uppercase) for thing in thinglist" 
                                    ng-change="submitSelectedValThing()"
                                    required>
</select>

and here is how I'm trying to get the value that the user selected

$scope.selectThings.name;

but I get an undefined error in that line, the code used to work fine before I added that filter

here is my full controller

angular.module('MyApp')
    .controller('ThingCtrl', ['$scope',
        function ($scope) {


           $scope.submitSelectedValThing = function () {
            $scope.$watch('thing.Name', function (newVal, oldVal) {
                if (!$scope.thing.Name || newVal === oldVal) return;
                    // now do stuff here with $scope.selectedThing
                    console.log('the value is ' + $scope.selectThings.name);
            });
           console.log($scope.selectThings.name);

           };




         }]);

What you really want here is

<select ng-model="selectedThing" ng-options="formattedThingName as (thing.name | uppercase) for thing in thinglist"></select>

The selected value is now accessible via $scope.selectedThing

I'm not really sure about the outcome from your code, but my guess is that it was re-assigning the value of the uppercase filter to the thing.name.

You can add a watch to the value the drop down is bound to and then compare values in the expression evaluator like so:

        //
        // Handle dropdown on select
        $scope.$watch('selectThings.name', function (newVal, oldVal) {
            if (!$scope.selectThings.name || newVal === oldVal) return;
                // now do stuff here with $scope.selectThings.name
            );
        });

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