如何将数据绑定到角度的数组?

时间:2014-07-11 22:49:56

标签: javascript angularjs

我需要有两个下拉列表,每个列表最初包含1到9个整数。我想我可以使用以下内容来做到这一点:

<--html area-->
<select ng-repeat="num in MaxCupcakes">
    <option ng-model="num" />
</select> 

<select ng-repeat="num in MyCupcakes">
     <option ng-model="num" />
</select> 

<--script area -->

var app = angular.module("app", []);
app.controller('Ctrl', function() {

   $scope.MaxCupcakes = [1,2,3,4,5,6,7,8,9]; 
   $scope.MyCupcakes = [1,2,3,4,5,6,7,8,9]; 

});

一旦我将此设置正确,我想在MaxCupcakes中选择限制MyCupcakes中的数字。例如,如果我将最大杯形蛋糕设置为5,那么我只能在mycupcakes中选择1-5。

1 个答案:

答案 0 :(得分:2)

更好的方法是在第二个选择上使用过滤器。

<div ng-app ng-controller="Ctrl">
    <select ng-model="max">
        <option ng-repeat="num in MaxCupcakes" ng-click="changeMax(num)">
            {{num}}
        </option>
    </select>
    <select ng-model="foo>
        <option ng-repeat="num in MyCupcakes | limitTo:max">
            {{num}}
        </li>
    </select>
</div>

此外,您的阵列不应该有{}。这是ctrl应该是什么样子。

function Ctrl($scope) {
    $scope.MaxCupcakes = [1,2,3,4,5,6,7,8,9]; 
    $scope.MyCupcakes = [1,2,3,4,5,6,7,8,9];

    $scope.max = 9;
};