저는 md-select를 사용 중이며 값이 변경되면 특정 코드를 트리거해야합니다 (국가/상태 선택기 구축). 컨트롤을 통해 값을 변경할 때 잘 작동하지만 코드에서 모델을 변경하면 컨트롤에 값이 제대로 반영되어야합니다. 변경 코드를 트리거하기 위해 ng-change를 사용하고 있습니다 (사용자가 키보드를 클릭하지 않고 값을 변경할 수 있기 때문에 변경이 필요함). 문제는 코드에서 값을 변경하면 이벤트가 발생하지 않는다는 것입니다. 좀 더 복잡하게하기 위해, md-select는 지시문에 살기 때문에 여러 곳에서 설정을 사용할 수 있습니다. 여기 모델이 변경되면 md-select에서 변경을 트리거하는 방법은 무엇입니까?
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();
})
})();
}]
}
}]);
이 사용 예제 : 여기
<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>
이 지시어 코드입니다 :
<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에서 watch를 시도했지만 거기에 valueGetter 함수를 두었습니다. – Jason