简体   繁体   中英

Not getting default selected value of drop down list using angular.js

i am not getting the default value of my drop down list using angular.js. i am explaining my code below.

<th>
<select style="width:100%; border:none; font-weight:bold;" ng-options="sub.name for sub in noCourse track by sub.value" ng-model="search" ng-change="selectedCourseTable();" >
<option value="">Course Name</option>
</select>
</th>

Here I am fetching the data dynamically and bind them in select tag.The above code generates the following html output.

<select style="width:100%; border:none; font-weight:bold;" ng-options="sub.name for sub in noCourse track by sub.value" ng-model="search" ng-change="selectedCourseTable();" class="ng-valid ng-touched ng-dirty ng-valid-parse">
<option value class  selected="selected">Course Name</option>
<option value="Master of computer application" label="Master of computer application">Master of computer application</option>
<option value="Bachelor of Technology" label="Bachelor of Technology">Bachelor of Technology</option>
<option value="Master in Technology" label="Master in Technology">Master in Technology</option>
</select>

subjectController.js:

$scope.selectedCourseTable=function(){
        if($scope.search.value=='Bachelor of Technology'){
            alert($scope.search.value);
        }
        if($scope.search.value=='Master in Technology'){
            alert($scope.search.value);
        }
        if($scope.search.value=='Master of computer application'){
            alert($scope.search.value);
        }
        if($scope.search==''){
            alert($scope.search.value);
        }
    }

Here I can not check when i am selecting text as Course Name in ng-change event.Other select option i can check by using this line $scope.search.value but when user is selecting this default text Course Name it can not be check.Please help me to resolve this issue.

Removing the <option value="">Course Name</option> in your template and adding a corresponding default selection in your object list will fix this.

Wherever you set your noCourse :

$scope.noCourse = [{
    name :'Course Name',
    value: ''
}, /*rest of the values*/];
$scope.search = $scope.noCourse[0];

You would then need to modify the line before to now check the object:

// instead of this:
if ($scope.search == '') {
    alert($scope.search.value);
}

// do this
if ($scope.search.value == '') {
    alert($scope.search.value);
}

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