Reputation: 2431
Problem 1: (only occurs on Firefox, results vary in other browsers)
Every second refresh in the browser causes an empty option to be displayed as the default option. How can I fix this?
Problem 2: (occurs in all browsers)
What I want to do is to get the function to set the back to its default value. What happens though is that it sets "City" to 0 correctly, but it displays an empty option as the default option. Any reason why this is happening?
*Note: Try using different AngularJS versions, I have found changes depending on the AngularJS version
Final Outcome Wanted: Change the option to "---City---" on button click, without ever having a random empty option in the list.
angular.module("MyApp", []).controller("MyCtrl", function($scope) {
$scope.CityChange = function() {
$scope.City = 0;
};
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body ng-app="MyApp" ng-controller="MyCtrl">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<label>City</label>
<select ng-model="City" ng-init="City='0'">
<option value="0">---City---</option>
<option value="1">City 1</option>
<option value="2">City 2</option>
</select><br><br> {{City}}
<br><br>
<button ng-click="CityChange()">Change City</button>
</body>
</html>
Upvotes: 2
Views: 83
Reputation: 6620
You have to use $scope.City ="0";
. You are assigning an integer in your code.
angular.module("MyApp", []).controller("MyCtrl", function($scope) {
$scope.CityChange = function() {
$scope.City = 0;
};
//init
function init(){
$scope.City=0
};
init();
});
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body ng-app="MyApp" ng-controller="MyCtrl">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<script src="script.js"></script>
<label>City</label>
<select ng-model="City">
<option ng-value="0" disabled="disabled">---City---</option>
<option ng-value="1">City 1</option>
<option ng-value="2">City 2</option>
</select><br><br>
{{City}}<br><br>
<button ng-click="CityChange()">Change City</button>
</body>
</html>
Upvotes: 1