Search code examples
arraysangularjsangularjs-scopedynamic-scope

Get dynamic scope array variable value in angularjs


I have a scope array variable which i am trying to access dynamically. Its value has been already set.

Its like this.

$scope.setp = { arr: [] };
$scope.setp.arr[0] = "sample Value";

When I am trying to access it dynamically as below I get undefined.

console.log($scope['setp.arr[0]']);

However I am able to access it directly using the following.

console.log($scope.setp.arr[0]);

The way of dynamically getting value of scope variable works fine for others but fails when the variable name contains square brackets i.e. [ ].

I followed this example but no success for scope variable containing array or square brackets [ ].

Also dynamically setting of scope array variable using $parse service works fine as in below.

var scopeVariable = $parse('setp.arr[0]');
scopeVariable.assign($scope, "new Value");

Solution

  • This won't work console.log($scope['setp.arr[0]']); as its trying to access a property setp.arr[0]. You can access it like console.log($scope['setp']['arr'][0]);