用于下拉列表的angularjs嵌套级联指令
我想创建一个级联下拉指令用于下拉列表的angularjs嵌套级联指令,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我想创建一个级联下拉指令 <my-dropdown label="states" url="http://statelisturl"> <my-dropdown label="cities" url="http://citylisturl"> </my-dropdown> </my-dropdown> 但州将首先列出,当我选择一个州时,城市将从url中获取 从技术上讲,angularjs可以这样做吗?或者,我应该为每个下拉
<my-dropdown label="states" url="http://statelisturl">
<my-dropdown label="cities" url="http://citylisturl">
</my-dropdown>
</my-dropdown>
但州将首先列出,当我选择一个州时,城市将从url中获取
从技术上讲,angularjs可以这样做吗?或者,我应该为每个下拉列表单独设置指令?您可以这样做:
.directive("myDropdown", function() {
return {
restrict: "E",
require: ["myDropdown", "?^^myDropdown"],
template: "<select ng-options='opt as opt.label for opt in $ctrl.options' ng-model='$ctrl.selectedOption' ng-change='$ctrl.changed($ctrl.selectedOption)'></select><div ng-transclude></div>",
scope: true,
bindToController: {
url: "@",
label: "@"
},
controller: function($scope, $http) {
var _self = this;
_self.init = function() {
$http.get(_self.url).then(function(response) {
_self.options = response.data;
});
}
_self.parentChanged = function(item) {
var id = item.id;
$http.get(_self.url + "?id=" + id).then(function(response) {
_self.options = response.data;
});
}
},
link: function(scope, element, attrs, ctrls) {
var ctrl = ctrls[0];
var parentCtrl = ctrls[1];
if (parentCtrl) {
scope.$watch(function() {
return parentCtrl.selectedOption;
}, function(newval) {
if (newval) {
ctrl.parentChanged(newval);
}
});
} else {
ctrl.init();
}
},
controllerAs: "$ctrl",
transclude: true
}
});
指令(“myDropdown”,函数(){
返回{
限制:“E”,
要求:[“myDropdown”,“?^^myDropdown”],
模板:“”,
范围:正确,
bindToController:{
网址:“@”,
标签:“@”
},
控制器:函数($scope,$http){
var _self=这个;
_self.init=函数(){
$http.get(_self.url).then(函数(响应){
_self.options=response.data;
});
}
_self.parentChanged=函数(项){
var id=item.id;
$http.get(_self.url+“?id=“+id”)。然后(函数(响应){
_self.options=response.data;
});
}
},
链接:功能(范围、元素、属性、ctrls){
var ctrl=ctrls[0];
var parentCtrl=ctrls[1];
if(parentCtrl){
范围$watch(函数(){
返回parentCtrl.selectedOption;
},函数(newval){
if(newval){
ctrl.parentChanged(newval);
}
});
}否则{
ctrl.init();
}
},
controllerAs:“$ctrl”,
转移:对
}
});
编辑:我有一个工作示例我有几个问题,为什么要使用[“myDropdown”,“?^^myDropdown”]。第一个问题需要指令本身的控制器,因此它可以在
链接
功能中使用。第二个用于要求父级my下拉列表
指令。如果它不为null,则表示存在一个父级,因此它可以监视其所选的itemI要动态生成嵌套指令。这可能吗?数据将是嵌套指令的javascript对象。并生成ng repead
或其他方式?