0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the reply. But I have to display the corresponding div also.
Thank you, it's working. Can we have the name value as dynamic ?
What do you mean by that?
0

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.

1 Comment

Thank you for the reply. Here I have to display the corresponding div also. And the region value (us) is dynamic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.