AshBringer
AshBringer

Reputation: 2673

Angular get reference to $scope variable from select

I have a list :

$scope.selectlist = ["list1","list2","list3"];

Once I choose an element, I should display the list according to the select value knowing that I have these lists in my scope :

$scope.list1
$scope.list2
$scope.list3 

Any ideas to make it work ?

I thought doing :

    <div ng-repeat="i in selectedPerson">
       {{selectedPerson}}
    </div>

will work.

Fiddle

Upvotes: 0

Views: 72

Answers (4)

Bameza
Bameza

Reputation: 207

You just need to use javascript variable instead of $scope for your list1, list2, list3.

var list1 = [1,2,3,4,5];

var list2 = ['a','b','c','d','e','f','g'];

var list3 = ["hi","bye","whatever"];

$scope.selectlist = [list1,list2,list3];

http://jsfiddle.net/81t6cbjw/70/

Upvotes: 1

staskus
staskus

Reputation: 171

Change your template to this:

<div ng-app="myapp" ng-controller="FirstCtrl">
        <select ng-options="p for p in selectlist" ng-model="selectedPerson"></select>

        <div ng-repeat="i in this[selectedPerson]">
           {{i}}
        </div>
</div>

Upvotes: 1

Kasper Ziemianek
Kasper Ziemianek

Reputation: 1349

Your ng-repeat variable is i so You should put {{i}} instead of {{selectedPerson}}.

You should also get proper list from the scope, based on $scope.selectedPerson value. Try this :

$scope.getList = function() { return $scope[$scope.selectedPerson]; }

Fiddle

Upvotes: 1

Marin Takanov
Marin Takanov

Reputation: 1138

You can create a variable that holds all lists $scope.allLists and after a list is selected $scope.selectedList, just use the following syntax $scope.allLists[$scope.selectedList].

For example $scope.allLists = { list1: [...], list2: [...], list3: [...] } and $scope.selectedList = 'list1'.

Upvotes: 2

Related Questions