Home > Software design >  Display name instead ID modal dropdown in angularjs
Display name instead ID modal dropdown in angularjs

Time:04-20

there is a dropdown of country and state when I select country of name I have to pass id of country but after click event it should pass id but display as name how can I make it please guide

<md-select name="state" id="state" placeholder="Select a state" md-no-asterisk="true"
        ng-change="getCounties(state)" ng-model="state">
        <md-option ng-repeat="item in state track by id"
            value="{{item.id}}">
            {{item.name}}
        </md-option>
    </md-select>
    
    {{AddressState}} /* This should be name instead of value how can i display this ? */
    <div  ng-click="edit()">
        Edit</a></div>
    
        controller.ts :
        $scope.AddressState = state;

CodePudding user response:

Don't use state as your ng-model since state is already your data source. Consider instead using an object to capture all user input, with state as a property. Your ng-model will capture the ID on user selection, which is what you want, and you can use that to get the state name.

angular.module('myApp', [])
  .controller('myCtrl', ['$scope', function($scope) {
    $scope.userInput = {
      state: {}
    };
    $scope.state = [{
      "name": "Califoria",
      "id": 1
    }, {
      "name": "Texas",
      "id": 2
    }]

    $scope.getCounties = function() {
      // $scope.userInput.state is updated autmatically with the ID
      console.log($scope.userInput)
      // the associated data can be found using 
      let state = $scope.state.find(s => s.id == $scope.userInput.state)
      $scope.selectedState = state.name; // for display

    }
  }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <select ng-model="userInput.state" ng-change="getCounties()">
    <option ng-repeat="item in state" value="{{item.id}}">
      {{item.name}}
    </option>
  </select>

 <p> {{selectedState}} </p>
</div>

  • Related