Search code examples
angularjsangularjs-select

angularjs auto select drop down


in below function i got a response and length of perfiosAnalysisData

function getPerfiosData() {

      var tribeId = vm.currentTribeId;

      getPerfiosAnalysisData(tribeId).then(function(response){
        vm.perfiosAnalysisData = response.data;
        /* Check Select Option Length */            
            $scope.lengthData = vm.perfiosAnalysisData.institutions.length;     
        /* Check Select Option Length */        
        vm.isPerfiosEnabled = response.is_enabled;
        setChartDataConfig();
        getDrawGraph();
      },function(err){
        if(err.status === 412) {
          vm.perfiosNotPermitted = true;
        }
      });
    }

so if length is 1 i want to auto select option and call the ng-change function.

<select class="perf-select" ng-model="viewProfileCtrl.monthsForm.institution"
                           ng-options="inst.institution.institution_id as inst.institution.name for inst in viewProfileCtrl.perfiosAnalysisData.institutions"
                           ng-change="viewProfileCtrl.setCurrMonthInsti(viewProfileCtrl.monthsForm.institution)">
                           <option value=""  selected>Select a Bank
                        </select>

How to achive this?


Solution

  • if lengthData equals to 1 then assign the first object to ng model variable and call ng change function like this

    function getPerfiosData() {
        var tribeId = vm.currentTribeId;
        getPerfiosAnalysisData(tribeId).then(function(response) {
            vm.perfiosAnalysisData = response.data;
            /* Check Select Option Length */
            $scope.lengthData = vm.perfiosAnalysisData.institutions.length;
    
    
            if ($scope.lengthData === 1) {
                $scope.viewProfileCtrl.monthsForm.institution = $scope.viewProfileCtrl.perfiosAnalysisData.institutions[0];
                $scope.viewProfileCtrl.setCurrMonthInsti($scope.viewProfileCtrl.monthsForm.institution);
            }
    
    
            /* Check Select Option Length */
            vm.isPerfiosEnabled = response.is_enabled;
            setChartDataConfig();
            getDrawGraph();
        }, function(err) {
            if (err.status === 412) {
                vm.perfiosNotPermitted = true;
            }
        });
    }