Reputation: 1453
I am new to Angularjs. I have tired show & hide div using dropdown select and it is working. But I don't have idea to show the default values.
Requirement : Initial stage I have to display the first option in the dropdown and show the respective div
HTML :
<div ng-app="myApp" ng-controller="MyCtrl">
<select name="name" ng-model="region.name" ng-dropdown required ng-change="changeme()"
<option ng-option value="us" selected="selected">us</option>
<option ng-option value="uk">uk</option>
</select>
<div id="one" ng-if="region.name == 'us'"> US based event</div>
<div id="two" ng-if="region.name == 'uk'"> UK based event</div>
</div>
JS:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope, $window, $element) {
$scope.changeme = function() {
//no code
}
});
Ref code: jsfiddle
Upvotes: 0
Views: 2167
Reputation: 22911
To set default values, simply assign them in your controller:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope, $window, $element) {
$scope.region.name = 'uk';
});
See updated jsfiddle here.
To answer your section question, the reason why it's not working is because you haven't actually initialed the object anywhere. When your code attempts to access region.name
, region
has not yes been defined, and causes the ng-if statement to no longer attempt to validate. To solve this, initialize the full object at the start:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope, $window, $element) {
$scope.region = {
name: 'us'
};
});
See updated jsfiddle here.
Upvotes: 1
Reputation: 2070
When you bind a scope variable into a select, it looks for the options that it contains.
On your code, $scope.region.name is empty or undefined, thus it doesn't match any of your defined options.
You can set the default value on your controller for ex:
$scope.region.name = "us"
The select now knows what is selected on load.
Upvotes: 0