Sam
Sam

Reputation: 15770

AngularJS - Get $scope variable from string

So say I have a $scope variable defined like so:

$scope.data = {
    filter: {
        state: 'WA',
        country: 'US'
    }
};

How do I access that in a separate service by string? e.g. data.filter in the context of the $scope.

So say I have a service method like so:

function doSomething($scope, variableName) {
    // I want to access $scope[variableName] here??
}

I would call it from the controller like so:

service.doSomething($scope, 'data.filter');

Upvotes: 6

Views: 19104

Answers (2)

Nik Kashi
Nik Kashi

Reputation: 4596

You can access the variable with String via this snippet

var objAddress=variableName.split('.');
var yourVar=$scope.$eval(objAddress[0])[objAddress[1]];

Upvotes: -1

jgawrych
jgawrych

Reputation: 3542

You will want use $eval:

function doSomething($scope, variable) {
  var data = $scope.$eval(variable);

  // this logs {state: "WA", country: "US"}
  console.log(data);
}

However, if you wanted to do some functionality every time the contents changes, it would be preferable to use $watch

function doSomething($scope, variable) {
  $scope.$watch(variable, function(data) {
    // this logs {state: "WA", country: "US"}
    console.log(data);
  });
}

Upvotes: 18

Related Questions