sam
sam

Reputation: 3

Get dynamic scope variable value angularjs

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

Upvotes: 0

Views: 6936

Answers (2)

User2
User2

Reputation: 1293

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

});

Upvotes: 0

Brocco
Brocco

Reputation: 64843

This will get the value for you dynamically:

var getMyValue = $scope[$scope.myarray[0].id];

Upvotes: 1

Related Questions