4

我想要实现的是用依赖于“父”组合框的项目填充子组合框。

为了澄清这个问题,我在这个链接下创建了一个小提琴

每次组合框“组”发生更改时,都应填充组合框“项目”。

控制器:

function Controller( $scope ) {    
    var groups = [ ]; // ommitted for the sake of clarity
    
    $scope.groups = groups;                 // <- linked to cboGroup
    $scope.currentGroup = groups[0];        // <- should be updated from combobox
    $scope.currentItems = $scope.currentGroup.Items;  // <- linked to cboItems
    $scope.currentItem = $scope.currentItems[0];      // <- should be updated from cboItems
}

看法

<select data-ng-model="currentGroup" data-ng-options="group.Name for group in groups"></select>
<select data-ng-model="currentItem" data-ng-options="item.Name for item in currentItems"></select>

我不能以声明的方式将其变为现实。这应该可以在没有魔法 JavaScript 的情况下工作 - 不是吗?

谢谢您的支持

4

4 回答 4

7

您应该参考currentGroup来填充项目组合框中的选项:

<select data-ng-model="currentItem" data-ng-options="item.Name for item in currentGroup.Items"></select>

你根本不需要$scope.currentItems。所以只需将控制器内的最后两行更新为:

$scope.currentItem = $scope.currentGroup.Items[0];  

现在要删除空选项,使用超级简单和轻量级的ng-change

<select data-ng-model="currentItem" data-ng-options="item.Name for item in currentGroup.Items" ng-change="groupChanged()"></select>

在控制器中定义相应的更改处理程序:

$scope.groupChanged = function(){
    $scope.currentItem = $scope.currentGroup.Items[0];
}
于 2013-08-06T14:17:29.243 回答
1

这应该是你所追求的:

http://jsfiddle.net/TsxTU/1/

它的工作原理是在语法中使用selectas labelfor 。所以对于第一个选择框,无论用户选择什么都将成为绑定到的对象。类似的事情是为itemgroupcurrentGroupcurrentItem

然后,我们可以选择使用$watch表达式来通知该更新,并确保currentItem更新到新组Items数组中的第一项。

于 2013-08-06T14:32:20.900 回答
1

您可以像这样向控制器添加观察者。当您选择第一个下拉列表的不同值时,您也可以删除空项目。

$scope.$watch('currentGroup', function () {
    $scope.currentItems = $scope.currentGroup.Items;
    $scope.currentItem = $scope.currentGroup.Items[0];
});

Demo

于 2013-08-06T14:20:07.647 回答
0

此类问题还有其他解决方案。那就是广播。

获得数据后进行广播。在此示例中,数据来自 Ajax 调用。

$http.get('/SampleProgram/get_all_users').success(function(rsList){
       $scope.users =  rsList;
       $scope.$broadcast('I got all the users');
    });

应该有听众总是对您的广播信息保持警惕。

$scope.$on('I got all the users', function () {
        alert("Hey All the users are here already let's make another ajax call with those users");
    })
于 2018-03-26T11:13:48.683 回答