处理ng-repeat中另一个select元素的选项

时间:2015-08-10 14:04:06

标签: angularjs

我想实现类似的目标,但不知道我该怎么做。在ng-repeat里面我有2个选择列表,基于第一个选择的选择值我需要加载第二个选择的内容,JSP代码是

<div ng-repeat="obj in TypeList">
    <select ng-change="handleChange()">
        <option ng-repeat="c in cList" value="{{c.id}}" ng-disabled="!c.enabled" ng-selected="c.id == TypeList[0].id">{{c.name}}</option>
    </select>
    <select ng-model="outMessageType[obj]" ng-options="t.id as t.name for t in outTypes"></select>
</div>

我需要在handleChange()方法中发送一个ajax调用,并且在成功时,我需要刷新第二个选择列表,但仅限于通过TypeList生成的这个项目。

js code:

$scope.handleChange = function(data) {
    $http({
        method: 'GET',
        url: 'url',          
    }).success(function(data, status, headers, config) {
        $scope.outTypes = data.types;
    }
}

当我尝试这样做时,它会更新ng-repeat生成的所有项目的第二个选择列表的值。

1 个答案:

答案 0 :(得分:0)

检查工作演示:JSFiddle

使用ng-change捕获更改事件并检索第二个选择列表的选项。使用对象选择嵌套选项和模型。

angular.module('Joy', [])
    .controller('JoyCtrl', ['$scope', '$http', function ($scope, $http) {
    $scope.options = [0, 1, 2, 3, 4];
    $scope.firsts = {};
    $scope.seconds = {};
        $scope.secondOptions = {};
    $scope.loadSecond = function (userId, index) {
        $http.get('http://jsonplaceholder.typicode.com/posts?userId=' + userId).then(function (data) {
            $scope.secondOptions[index] = data.data;
        });
    };
}]);

HTML:

<div ng-app="Joy" ng-controller="JoyCtrl">
    <div ng-repeat="i in [0,1,2]">
        <select ng-model="firsts[i]" ng-change="loadSecond(firsts[i], i)">
            <option ng-repeat="opt in options" value="{{$index}}" name="{{$index}}">User {{opt}}</option>
        </select>Selected: {{first}}
       Posts of this user {{secondOptions[i].length}}:
        <select ng-model="seconds[i]">
            <option ng-repeat="opt in secondOptions[i]" value="{{$index}}" name="{{$index}}">{{opt.title}}</option>
        </select> <hr>
    </div>
</div>
相关问题