我的json数据看起来像
[{name:“ a”,内容:[{name:“ b”,内容:[{name:“ c”,id:1},{...}]},{...}]},{名称:“ ...”,内容:[...]}]
我想将其选择为“ a”和“ b”均为optionGroup,仅“ c”为option。
像这样:
一种
-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);
});
});
});
}
}
});
它工作正常,选择其他选项时,可以看到范围更改。
但是我发现我无法设置选择的初始化值,然后发现我无法随时设置任何选择来控制“选择”,选择似乎成为单向绑定,但我需要将其变为双向绑定。
样本jsfidle在这里:http://jsfiddle.net/sunny_jerry/SHxBp/
我该如何解决?
最佳答案
这是使其工作的一种方法,只需在choice
上设置观察者
$scope.$watch( 'choice', function( val ) {
elm.val( val );
});
http://jsfiddle.net/SHxBp/2/
关于javascript - 使用自定义指令后angularjs ng-model不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16702373/