2
我正在使用md-select,并且在值更改时需要触发某些代码(构建国家/州选择器)。当我通过控件更改值时,它的工作正常,但我还需要在模型从代码更改时正确地反映这些值。我使用ng-change来触发更改代码(需要更改,因为用户可以在不点击的情况下更改键盘上的值)。问题是,当从代码更改值时,事件不会被触发。为了让事情更复杂一些,这些MD选择符存在一个指令,允许我在几个地方使用这个设置。如何在模型更改时在md-select上触发ng-change?
这里是我的指令模板:
<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>
这里的指令代码:
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();
})
})();
}]
}
}]);
下面是一个使用示例:
<country-state-input country-model="app.location.countryId" state-model="app.location.stateId" input-form="locationsForm"></country-state-input>
而且OptionService.getCountries()返回这样的事情(州名单被缩短):
[
{
"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"
}
]
}
]
基本上,我试图找出是否有办法触发onCountrySelected,将涵盖所有3个用例。
谢谢瓦列里!我实际上在ctrl.countryModel上试过了一个手表,它没有工作,但把valueGetter函数放在那里。 – Jason