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);
  });
}
Sign up to request clarification or add additional context in comments.

7 Comments

I actually wanted to do an angular.forEach on the item, so I used $eval and it seems to work? And problems with that?
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.
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.
@Chandermani - So how do you pass objects from $scope into services to be $watched?
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.
|
-1

You can access the variable with String via this snippet

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

1 Comment

This is answer, not question!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.