0

I have array of object which contains number of scope variable name in it. All the scope variable value has already been set before.

Something like this :

$scope.myarray = [{'id':'myname1'},{'id':'myname2'}];
$scope.myname1 = 'John';
$scope.myname2 = 'Rick';

Now if I want to get value of the scope variable which within the 'id' of 'myarray',what should I do?
I have already tried this

var getMeMyValue = $scope[myarray[0]];

Something like this,but it didnt help.
I have seen in this example that how to set scope variable dynamically
But I didnt get anything about how to get value dynamically

Please help me with this,Thanks!!

P.S. Here I'm dynamically getting my scope variable so there is no way that I can access them directly to get their value

7
  • it work $scope.myarray = ['myname1','myname2']; var getMeMyValue = $scope[myarray[0]];
    – Grundy
    Commented May 26, 2015 at 11:57
  • can you show working sample how you try, and what error you have?
    – Grundy
    Commented May 26, 2015 at 11:58
  • Or can you please create an sample in jsfiddle.net? Commented May 26, 2015 at 12:01
  • Thanks @grundyGrundy, for consideration. Actually i have scope variable that assigned to several html component (textbox,combobox,etc) as per they created dynamically and I set the id same as the scope variable. I also stored these variables in a array above shown manner.
    – sam
    Commented May 26, 2015 at 12:16
  • can you provide jsfiddle or plunker? now not quite clear where is problem in your code
    – Grundy
    Commented May 26, 2015 at 12:18

2 Answers 2

1

This will get the value for you dynamically:

var getMyValue = $scope[$scope.myarray[0].id];
2
  • I think this will solve my problem. Thanks @brocco and sorry that i cant gives you thumbs up..not enough reputation :P
    – sam
    Commented May 26, 2015 at 12:39
  • No problem, if this does solve your problem, please mark it as the accepted answer (even if you cannot upvote due to rep)
    – Brocco
    Commented May 26, 2015 at 12:52
0

Please check this http://plnkr.co/edit/ZwwuKRVwgD74ufY2GmB8?p=preview

Controller -

var app = angular.module('myApp', [ ]);

app.controller('myController', function($scope) {
  $scope.myarray = [{'id':'myname1'},{'id':'myname2'}];
  $scope.myname1 = "John;"
  var getMeMyValue = $scope[$scope.myarray[0].id];
  console.log(getMeMyValue);

});
2
  • your answer same as @Brocco answer
    – Grundy
    Commented May 26, 2015 at 12:27
  • Ohh yes.. I have not checked.
    – User2
    Commented May 26, 2015 at 12:30

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.