admin管理员组

文章数量:1434949

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 plicate 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.

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 plicate 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.

Share Improve this question asked Sep 30, 2016 at 22:53 JasonJason 2,6174 gold badges43 silver badges48 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

You could use $scope.$watch

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

本文标签: javascriptHow to trigger ngchange on mdselect when model is changedStack Overflow