Search code examples
javascriptangularjsangularjs-scopeeval

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.


Solution

  • 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();      
        });  
    });