我正在尝试使用angular指令实现经典的Country > State > City
组合框。
我愿意通过自定义属性对name/depends-on
链接它们,但我不知道是否有更好的表单。
我的HTML如下:
<div ng-app="app" ng-controller="Ctrl">
<multiselect source-url="/countries.json" auto-init="true" name="Contries">
<select multiple ng-model="$parent.selectedOptions" ng-change="$parent.handleChange()">
<optgroup ng-repeat="(continent, countries) in $parent.optionList" label="{{continent}}">
<option ng-repeat="country in countries" value="{{country.code}}">
{{country.code}} - {{country.name}}
</option>
</optgroup>
</select>
</multiselect>
<multiselect source-url="/states.json" depends-on="Countries" name="States">
<select multiple ng-model="$parent.selectedOptions" ng-change="$parent.handleChange()">
<optgroup ng-repeat="(continent, countries) in $parent.optionList" label="{{continent}}">
<option ng-repeat="country in countries" value="{{country.code}}"> {{country.code}} - {{country.name}}
</option>
</optgroup>
</select>
</multiselect>
</div>
Javascript:
app.directive('multiselect', function () {
return {
restrict: 'E',
transclude: true,
scope: {
sourceUrl : '@',
autoInit : '@',
dependsOn : '@'
},
controller: ['$scope', '$element', '$attrs', '$transclude', '$http', function ($scope, $element, $attrs, $transclude, $http) {
$scope.handleChange = function handleChange() {
console.log($scope.selectedOptions)
}
console.log($scope.dependsOn)
function updateSource() {
const config = {
params : {}
}
if ($scope.dependsOn) {
// how do I get dependsOnValue?????
config.params[$scope.dependsOn.toLowerCase()] = $scope.dependsOnValue
}
$http.get($scope.sourceUrl, config)
.then(function (response) {
$scope.optionList = response.data
})
}
if ($scope.autoInit) {
updateSource()
}
}],
template: '<ng-transclude></ng-transclude>'
}
})
问题是:我如何关注Countries
中的更改才能获得更新States
的价值?
我试图让它尽可能重复使用。