【发布时间】:2013-05-18 03:08:30
【问题描述】:
我的 json 数据看起来像
[{name:"a", content:[{name:"b", content:[{name:"c", id:1}, {...}]}, {...}] },{名称:“...”,内容:[...]}]
我想把它放到一个选择中,其中“a”和“b”都是选项组,只有“c”是选项。 像这样:
一个
-b
c
jsfidle 示例在这里:http://jsfiddle.net/sunny_jerry/SHxBp/
似乎“ngOptions”不能满足我的要求,所以我定义了一个这样的指令:
<select class="compo-tree" x-compo-tree colleges="colleges" ng-model="choice"></select>
directive('compoTreeNew', function($compile) {
return {
restrict: 'A',
scope: {
colleges: "=colleges",
choice: "=ngModel"
},
link: function($scope, elm){
$scope.$watch("colleges", function(){
angular.forEach($scope.colleges, function(college) {
elm.append($("<optgroup>").attr("label", college.name));
angular.forEach(college["departments"], function(department) {
var optGroup = $("<optgroup>").attr("label", '- ' + department.name);
angular.forEach(department['disciplines'], function(discipline) {
optGroup.append($("<option>").attr("value", discipline.id).text(discipline.name));
if (!$scope.choice) { $scope.choice = discipline.id; }
});
elm.append(optGroup);
});
});
});
}
}
});
它工作正常,当我选择不同的选项时,我可以看到范围的变化。
但是我发现我无法设置choice的初始化值,然后我发现我无法设置任何选择来控制“select”,choice似乎变成了单向绑定但我需要它变成了两个-方式绑定。
jsfidle 示例在这里:http://jsfiddle.net/sunny_jerry/SHxBp/
我该如何解决?
【问题讨论】:
-
要记住的一点是每个元素只有一个作用域。由于您的
compoTreeNew指令使用隔离范围,因此这是元素上的唯一范围,并且它与父范围断开连接。这可能会破坏同一元素上的内置 ng-model/selectController 功能。 -
@darkporter 你的意思是我需要自己实现 ng-model 吗?
标签: javascript angularjs angularjs-directive directive