Choosing an option in a selection box updates the rest

advertisements

I have just started building my first app in angular JS and I have hit a road block. I have been trying to create a page like shown below:

I dynamically create the controls shown in the html code below:

    <!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>Compare Tickers</h1>
    <hr/>
    <div ng-controller="MainCtrl">
            <ul>
                <li id="control{{$index}}" ng-repeat="oneTickerInfo in tickerInfo">
                    Ticker Info : <input ng-model="oneTickerInfo.ticker">
                    <select id="selector{{$index}}" ng-model="caches.cache">
                        <option id="options{{$index}}" ng-repeat="cacheName in caches">{{cacheName.cache}}</option>
                    </select>
                    <select ng-model="boxes.box">
                        <option ng-repeat="boxName in boxes">{{boxName.box}}</option>
                    </select>
                    [<a href ng-click="colors.splice($index, 1)">X</a>]
                </li>
                <li>
                    [<a href ng-click="colors.push({})">add</a>]
                </li>
            </ul>
            <hr/>
    <div ui-view></div>
    </div>
</body>
</html>

This is the code for the controller

'use strict';

var app = angular.module('qaweb3App');

  app.controller('MainCtrl', function Hello($scope, $http) {
        $scope.tickerInfo = [
            {id:'1', cache:'adx',host:'tpa27'},
            {id:'1', cache:'asx',host:'tpa27'}
        ];

        $scope.caches = [
            {cache:'adx'},
            {cache: 'taiwan'}
        ]

        $scope.boxes = [
            {box:'tpa27'},
            {box:'tpb27'}
        ]

    });

I am sorry as I am not able to post the images because I dont have enough reputation to post the same.

So the problem is whenever I try to select an element from the first dropdown for caches it also populates the second dropdown.Same is the case with the other dropdown for boxes. Am i not using ng-model correctly.

Not sure whats going on. Please Help! Thank You!


The main problem is that you're sharing an object property for ng-model across all of your select options. Instead, you need to set a unique model for each.

Set the model to the properties of each individual item in your ng-repeat item oneTickerInfo. You should also use ng-options to populate the select options.

<select ng-model="oneTickerInfo.cache"
ng-options="cache.cache as cache.cache for cache in caches"></select>

<select ng-model="oneTickerInfo.host"
ng-options="box.box as box.box for box in boxes"></select>

As long as your tickerInfo object has properties/values for both, no default option needs to be set in the controller for the select, since the object itself will provide its own default values.

Plunker demo

Angular docs on select (including ngOptions)