AngularJS - get $ scope variable from string

So, I have a $scope variable defined like this:

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

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

So, say I have a service method:

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

I would call it from the controller as follows:

 service.doSomething($scope, 'data.filter'); 
+6
source share
2 answers

You need to use $ eval :

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

However, if you want to perform some functionality every time you change the content, 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); }); } 
+17
source

You can access the variable with String using this snippet

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

Source: https://habr.com/ru/post/971159/


All Articles