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');
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);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With