Javascript 在angular.js中创建级联dropbox
我有一个嵌套对象,我正试图将其转换为级联选择框Javascript 在angular.js中创建级联dropbox,javascript,angularjs,Javascript,Angularjs,我有一个嵌套对象,我正试图将其转换为级联选择框 "A": { "a1": 1, "a2": 2 }, "B": { "b1": { "b11": 111 }, "b2": { "b222": 222 } } }; 用户应选择值,直到达到某个值为止。收集的深度未知 例如-B->b1->b11->111。在本例中,我们有三个选择框。A->a1->1-只有两个。
"A": {
"a1": 1,
"a2": 2
},
"B": {
"b1": {
"b11": 111
},
"b2": {
"b222": 222
}
}
};
用户应选择值,直到达到某个值为止。收集的深度未知
例如-B->b1->b11->111。在本例中,我们有三个选择框。A->a1->1-只有两个。在上一级别中选择一个值后,将显示每个框
我用一个模板试过了,这是实现递归的唯一方法。我需要scope.value的最终值
这不起作用,部分原因是angular.isObject没有返回任何结果
谢谢你的帮助 在这样的表达式中不能调用angular.isObject。Angular接下来要查找的是父控制器作用域中的函数$scope.Angular.isObject,正如value实际上是$scope.value一样
你能做的是:
在selectCtrl中:
$scope.isObject=angular.isObject;
在cascading_combo.html中:
有关最终结果,请参见
使现代化
上面的示例不能以动态方式工作,因为模板一旦添加就无法删除。以下是使用ngRepeat和单个列表的非补偿方法:
HTML
JS
谢谢你的提示@Mouagip。如果选择A,则会出现a1、a2,但如果将第一个选择更改为B,则不会发生任何事情。是否可以跨ng include作用域将所选值绑定在一起?另外,控制器中不存在该值。-也许这里使用的模板是错误的。尝试为此使用指令。也许这有帮助?我会尝试使用ngRepeat进行您提到的动态更改。也许我可以让一个例子工作…@haki抱歉,不能让它像那样运行。我的破衣服好像不管用。也许你考虑不使用回忆?如果深度不均匀,你会怎么做?比如说。ngRepeat只有一个数组,每个select只知道其深度索引ngRepeat的$index。如果选择某个值,则删除所有较深的数组元素,并更改具有当前深度的数组元素。这个解决方案也不是很好,但我看不出如何做得更好。
<script type="text/ng-template" id="cascading_combo.html">
<h5> current </h5>
<pre>{{current | json}}</pre>
<select ng-model='value' ng-options="v as k for (k,v) in current"></select>
<pre> type of {{value}} : {{angular.isObject(value)}}</pre>
<span ng-if="angular.isObject(value)" ng-init='current=value' ng-include='"cascading_combo.html"'>
</span>
</script>
<div ng-app="app" ng-controller="ctrl">
<div recoursive-select="" ng-repeat="item in selected"></div>
</div>
app = angular.module('app', []);
app.controller('ctrl', function($scope) {
$scope.selected = [/** insert first element here **/];
});
app.directive('recoursiveSelect', function() {
return {
template: '<select ng-model="newSelected" ng-options="key for (key, value) in data"></select>',
controller: function($scope) {
// workaround to strip the $$hashKey of ngRepeat
$scope.data = angular.fromJson(angular.toJson($scope.item));
// watch for selecting a value
$scope.$watch('newSelected', function(newSelected) {
// watch is always called initially. do this to prevent infinite loop
if (!newSelected) return;
var nextIndex = $scope.$index + 1;
// remove all "deeper" elements plus the one on this level
while ($scope.selected.length > nextIndex) {
$scope.selected.pop()
}
// add the newly selected element on this level
$scope.selected.push(newSelected);
});
}
};
});