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