Jason
Jason

Reputation: 2617

How to trigger ng-change on md-select when model is changed?

I'm using md-select and need to trigger certain code when the value changes (building a Country/State selector). I have it working fine when I change the value through the control but I also need to have the controls reflect the values properly when the model is changed from code. I'm using ng-change to trigger the change code (need ng-change as user can change the value from the keyboard without clicking on it). The problem is that when the value is changed from the code, the event isn't fired. To complicate things a bit more, the md-selects live in a directive to allow me to use the setup in several places.

Here's my directive template:

<md-input-container class="md-block">
    <label>Country</label>
    <md-select name="country" ng-model="countryState.countryModel" ng-change="countryState.onCountrySelected()">
        <md-option ng-repeat="country in countryState.countries" ng-value="country.itemId">
            {{ country.name | translate }}
        </md-option>
    </md-select>
</md-input-container>

<md-input-container class="md-block">
    <label>State</label>
    <md-select name="state" ng-model="countryState.stateModel" ng-disabled="countryState.countryModel == null">
        <md-option ng-repeat="state in countryState.states" ng-value="state.itemId">
            {{ state.name | translate }}
        </md-option>
    </md-select>
</md-input-container>

Here's the directive code:

angular.module('myapp.shared')

    .directive('countryStateInput', [function () {
        return {
            restrict: 'E',
            templateUrl: 'app/shared/inputs/countryState/country-state-input.directive.html',
            transclude: false,
            scope: {
                coordsForm: '=',
                countryModel: '=',
                stateModel: '='
            },
            bindToController: true,
            controllerAs: 'countryState',
            controller: ['$scope', '$document', 'OptionService', function($scope, $document, OptionService) {
                var ctrl = this;

                // Properties
                ctrl.countries = null;
                ctrl.states = [];
                ctrl.selectedCountryIndex = null;

                ctrl.onCountrySelected = function() {
                    // Get the index of the country
                    for (var i = 0; i < ctrl.countries.length; i++) {
                        if (ctrl.countryModel === ctrl.countries[i].itemId) {
                            // If a different country was chosen, clear the selected state
                            if (i !== ctrl.selectedCountryIndex) {
                                ctrl.stateModel = null;
                                angular.copy(ctrl.countries[i].states, ctrl.states);
                            };

                            // Save the index of the selected country
                            ctrl.selectedCountryIndex = i;
                            return;
                        }
                    }
                };

                // Initialization
                var initialize = function () {
                    OptionService.getCountries().then(
                        function (result) {
                            ctrl.countries = result;
                        });
                };

                (function () {
                    $document.ready(function () {
                        initialize();
                    })
                })();
            }]
        }
    }]);

Here's a usage example:

<country-state-input country-model="app.location.countryId" state-model="app.location.stateId" input-form="locationsForm"></country-state-input>

And OptionService.getCountries() returns something like this (states lists are shortened):

[
    {
        "itemId": 1,
        "name": "CA",
        "states": [
            {
                "itemId": 1,
                "name": "CA_ON",
                "abbreviation": "ON"
            },
            {
                "itemId": 2,
                "name": "CA_QC",
                "abbreviation": "QC"
            }
        ]
    },
    {
        "itemId": 2,
        "name": "US",
        "states": [
            {
                "itemId": 14,
                "name": "US_AL",
                "abbreviation": "AL"
            },
            {
                "itemId": 15,
                "name": "US_AK",
                "abbreviation": "AK"
            }
        ]
    }
]

Basically, I'm trying to figure out if there's a way to trigger onCountrySelected that will cover all 3 use cases.

Upvotes: 2

Views: 7880

Answers (1)

Valery Kozlov
Valery Kozlov

Reputation: 1577

You could use $scope.$watch

$scope.$watch(
   function valueGetter(){
      return smth;
   },
   function onChange(newSmth, oldSmth){
   }
)

Upvotes: 3

Related Questions