Dejan Stuparic
Dejan Stuparic

Reputation: 595

Access variable by string in AngularJS

I want to access and update state of variable.

function valueChange(sourceVariable, targetVariable, sourceUnit) {
    $scope[targetVariable] = measure($scope[sourceVariable] + sourceUnit + ".").kilograms();        
}); 

This function is called whenever something is entered in input field (on tab out). But the problem is value in input field that is bound to $scope[targetVariable] is not updated until you click inside input box.

PS: If I use variable in regular fashion it works fine.

Upvotes: 0

Views: 784

Answers (1)

Max Koretskyi
Max Koretskyi

Reputation: 105497

You probably need to udpate your variable inside $scope.$apply:

function valueChange(sourceVariable, targetVariable, sourceUnit) {
    $scope.$apply(function() {
          $scope[targetVariable] = measure($scope[sourceVariable] + sourceUnit + ".").kilograms();      
    });  
}); 

Upvotes: 1

Related Questions