Angular中的动态选择框

时间:2015-12-08 13:59:42

标签: jquery angularjs

我正在学习Angular,并在jQuery中有动态选择框,询问孩子的数量。选择框根据选择的数量动态变化,然后询问孩子的年龄。

这是正常工作但是看到它们是动态的,如果页面被重置,它们会在我的Angular应用程序中失去状态。

我正在为其他数据使用会话cookie。

将此包装成Angular的最佳方法是什么?

$(document).on("change", "#children", function() {
    var $div = $('.add-wrap'); //Select the appending div
    var $select = $('<div class="pull-left col-xs-1 col-sm-1 col-lg-1"><fieldset class="form-group">'
        +'<label class="ach-search" for="children">Age</label>'
        +'<select class="form-control" name="age" id="age">'
        +'<option value="0">0</option>'
        +'<option value="1">1</option>'
        +'<option value="2">2</option>'
        +'<option value="3">3</option>'
        +'</select>'
        +'</fieldset></div>').appendTo('.add-wrap')
    $select.clone();
    var index = this.selectedIndex; //get the number of select
    $div.empty(); //Erase old select
    if(!index) return; //Stop the code if the number of child is 0
    for(var u=0; u<index; u++){//Get the number of child
        var $clone = $select.clone(); //Clone the template
        $clone.appendTo($div);
    }
}).trigger('change');

2 个答案:

答案 0 :(得分:1)

好的,让我们给你一个提示。

以下是如何使用角度进行操作(未经测试,但只是为了让您明白这一点):

Number of children 
<input type="number" ng-model="childrenCount" ng-change="updateChildren()" />
<select ng-repeat="c in children" ng-model="c.age">
   <option ng-repeat="a in possibleAges" ng-value="a">{{a}} years</option>
</select>

在你的控制器中:

$scope.updateChildren = function(){
    var c = $scope.childrenCount;
    if(!$scope.children)
        $scope.children = [];
    else if($scope.children.length>c)
        $scope.children.splice(c,$scope.children.length-c); // remove last elements
    while($scope.children.length<c)
        $scope.children.push({age:1}); // add children
};
$scope.possibleAges= [1,2,3,4];

使用这个,$ scope.children包含一个对象数组,每个对象都有一个&#39; age&#39;属性绑定到生成的选择框之一。

你可以看到更多的jQuery。

答案 1 :(得分:0)

Angular有一个内置指令,用于动态生成select元素中的选项列表。它被称为ng-options

相关问题