Sujit Y. Kulkarni
Sujit Y. Kulkarni

Reputation: 1386

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

The scenario is:

1.Load content from controller into <select>. 2.Append every selected item in the dropdown, to a <p> tag, such that it looks like a list

.

First part is done right. Now I'm not getting how to 'append' the selected item. Until now what I could do is, display the selected item in a

tag. But new item replaces the old, where I want it to be added next to the previous.

Markup

<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>

Controller

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']
                    },
            ]
    });

How to achieve this?

Upvotes: 0

Views: 220

Answers (1)

asafge
asafge

Reputation: 1139

When you use {{selectedItem.name}}-{{selectedQty}} you bind the data from the current scope to this location in your HTML file. This is not what you want to do (right?), because you want to append all selected values when they are selected.

Try adding something like ng-change="update()" to your <select> element, and in the controller have a function that appends selected items, on the scope:

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

Not sure it's the exact syntax but hopefully you get the idea.

Upvotes: 1

Related Questions