crowsfeet
crowsfeet

Reputation: 203

Set dropdown based on $scope match

I have a table that displays two columns using ng-repeat.

First column is a list of items pulled from one source.

Second column is a select element pulled from a second list.

What I want to do is automatically select an option in the dropdown, if it matches what is displayed in the left column.

I put together a fiddle: https://jsfiddle.net/raz1j9rt/1/

Here is my HTML:

<header>
    <title>myTittle</title>
</header>
<body ng-app='myApp' ng-controller='myController'>
    <div class="col-md-10 col-md-offset-1">
        <div>
            <form>
                <table class="table  table-striped">
                    <thead>
                        <th>From File</th>
                        <th>Map To</th>
                    </thead>
                    <tr class="selector-row" ng-repeat="(key,value) in List1">
                        <td><span id="myspan">{{value}}</span>

                        </td>
                        <td style="padding:10px;">
                            <select name="repeatSelect" id="repeatSelect" ng-model="data[value]" class="form-control">
                                <option ng-repeat="(key,value) in Match" value="{{value}}">{{value}}</option>
                            </select>
                        </td>
                    </tr>
                </table>
            </form>{{ data }}</div>
    </div>
</body>

Here is my JS:

var app = angular.module('myApp', [])
app.controller('myController', ['$scope', function ($scope) {
    $scope.data = {};

    $scope.List1 = ['product1', 'product2', 'product3', 'product4', 'product5'];
    $scope.Match = ['product1', 'somethtingElse1', 'product3', 'somethingElse2', 'product5'];


}])

Not really sure where to start on this...

Upvotes: 0

Views: 667

Answers (1)

David Boskovic
David Boskovic

Reputation: 1529

Expanding on Claies point, here's a working fiddle.

https://jsfiddle.net/dboskovic/raz1j9rt/2/

Add this to your controller.

// setup default matches
angular.forEach($scope.List1, function(v){
    $scope.data[v] = $scope.Match.filter(function(d){
        if(d === v) return true;
        return false;
    })[0];
})

And then change your select to:

<select name="repeatSelect" id="repeatSelect" ng-model="data[value]" class="form-control" ng-options="x for x in Match"></select>

Upvotes: 1

Related Questions