vamshin
vamshin

Reputation: 3

AngularJs : how to trigger ng-change event for defaut selected value of ng-otons in dropdown

I have two dropdowns. Based on the selection of first dropdown value, second dropdown will populate its values. After selecting value from second drop down value, it will call ng-change event and fetching data and displaying the info in table. This is working fine.

But what I need is, in second down , I have to set a default value selected, need to trigger ng-change and display data in table.

Below is HTML code for dropdowns.

<SELECT ng-model="selectedRS" ng-options="x as x.rsName for x in rsData" data-ng-change="getSPList(selectedRS)">

<SELECT  ng-model="selectedSP" ng-options="x as x.displayName for x in spInfoList" ng-change="getSPInfo(selectedSP)"></SELECT>

Here I have a table to display info which will come from getSPInfo method

my controller method getSPInfo is

$scope.getSPInfo = function(selectedSubproduct) {
        $http({
                    method: 'GET',
                    url: getSPInfo.web ',params: {rsId: selectedSP.rsId,spId : selectedSP.id}}).
                    success(function(data, status, headers, config) {

                        $scope.spInfo = data;
                    }).
                    error(function(data, status, headers, config) {

                    });

                }

Thanks in advance!!

Upvotes: 0

Views: 1985

Answers (1)

Crhistian
Crhistian

Reputation: 1292

This is just one of those things you'll have to manually trigger. ng-change isn't triggering it because the value isn't being watched until after the controller is being initialized.

In your controller you can either manually invoke the function:

$scope.getSPInfo(your_default_value);

Or what I like to do is wrap it in an onInit function so that it is clear to anyone reading the code what is happening. You can also put in here any other code that needs to run when the controller is initialized.

function onInit(){
    $scope.getSPInfo(your_default_value);
}
onInit(); 

A third option if you're using ui-router for your routing is to put it in the onEnter function as part of the state definition object. This will run the function when you enter that state.

Upvotes: 1

Related Questions