如何从angular.js生成的下拉列表中将值附加到DOM

How to append values to DOM from dropdown generated by angular.js

本文关键字:DOM 下拉列表 angular js      更新时间:2024-02-17

场景是:

1.将控制器中的内容加载到<select>中。2.将下拉列表中的每个选定项目附加到<p>标记,使其看起来像列表

第一部分做得很好。现在我还不知道如何"附加"所选项目。到目前为止,我所能做的就是在

标签中显示所选项目。但新项目取代了旧项目,我希望它被添加到前一个项目的旁边。

标记

<div id='content' ng-app='MyTutorialApp' ng-controller='MainController'>
        <h1>My Shopping List</h1>
        <select ng-model='selectedItem' ng-options='obj.name for obj in Items'></select>
        <select ng-model='selectedQty'>
                <option ng-repeat="label in Items[selectedItem.id].attr">{{label}}</option>
        </select>
        <p>{{selectedItem.name}}-{{selectedQty}}</p>
</div>

控制器

app.controller("MainController",function($scope){
            $scope.inputValue="";
            $scope.selectedItem=0;
            $scope.selectedQty=null;
            $scope.Items=[
                    {
                        id:0,
                        name:'Sugar',
                        attr:['0.5 Kg','1 Kg', '2 Kg', '5 Kg']
                    },
                    {
                        id:1,
                        name:'Salt',
                        attr:['0.5 Kg','1 Kg', '2 Kg', '5 Kg']
                    },
                    {
                        id:2,
                        name:'Oil',
                        attr:['500 ml','1 Ltr', '5 Ltr']
                    },
                    {
                        id:3,
                        name:'T-Shirts',
                        attr:['S', 'M', 'L','XL', 'XXL']
                    },
            ]
    });

如何做到这一点?

使用{{selectedItem.name}}-{{selectedQty}}时,将当前作用域的数据绑定到HTML文件中的该位置。这不是您想要做的(对吗?),因为您希望在选择所有选定值时附加这些值。

尝试将类似ng-change="update()"的内容添加到<select>元素中,并且在控制器中有一个函数可以将所选项目附加到范围上:

$scope.selectedList = new Array();
$scope.update = function() {
   $scope.selectedList.push($scope.selectedItem.name)
}

不确定它的确切语法,但希望你能明白。