2

我的 json 数据看起来像

[{name:"a", content:[{name:"b", content:[{name:"c", id:1}, {...}]}, {...}]}, {名称:“...”,内容:[...]}]

我想把它放到一个选择中,其中“a”和“b”都是选项组,只有“c”是选项。像这样:

a
-b

 c

示例 jsfiddle 在这里: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似乎变成了单向绑定但我需要它变成双向绑定.

示例 jsfiddle 在这里:http: //jsfiddle.net/sunny_jerry/SHxBp/

我该如何解决?

4

1 回答 1

0

这是一种让它工作的方法,只需设置一个观察者choice

$scope.$watch( 'choice', function( val ) {
    elm.val( val );
});

http://jsfiddle.net/SHxBp/2/

于 2013-05-22T22:37:16.943 回答