6

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

2 Answers 2

18

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);
  });
}
7
  • I actually wanted to do an angular.forEach on the item, so I used $eval and it seems to work? And problems with that?
    – Sam
    Commented Jun 22, 2014 at 3:16
  • 1
    How forgetful of me for using $parse instead of $eval. Yes, eval works perfectly fine. If you look at the internal code, you'll see that $eval is just $parse, automatically using $scope as the context: return $parse(expr)(this, locals); I'll update with $eval.
    – jgawrych
    Commented Jun 22, 2014 at 3:25
  • Since services are singleton in angular, be very careful passing scope to services as the service may keep reference and scope may not get destroyed. Commented Jun 22, 2014 at 3:27
  • @Chandermani - So how do you pass objects from $scope into services to be $watched?
    – Sam
    Commented Jun 22, 2014 at 3:37
  • 1
    Services are source of information, and mostly $scopes are never passed to services. Data should be modified in service and other controllers should watch for these changes. Commented Jun 22, 2014 at 5:37
-1

You can access the variable with String via this snippet

var objAddress=variableName.split('.');
var yourVar=$scope.$eval(objAddress[0])[objAddress[1]];
1
  • This is answer, not question!
    – Nik Kashi
    Commented Jun 23, 2014 at 5:35

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.