Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Get $scope variable from string

Tags:

angularjs

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');
like image 707
Sam Avatar asked Jun 22 '14 02:06

Sam


1 Answers

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);
  });
}
like image 82
Jonathan Gawrych Avatar answered Nov 13 '22 05:11

Jonathan Gawrych