0

I am using extra function to handle keyboard input. It seems that value gets passed successfully but when I try to assign like this model += char; value it fails. Why?

$scope.keyboardBtn = function(char){

        if($scope.focusedInput.name == 'inputFirstName'){
            $scope.keyboardAction($scope.persons[$scope.focusedInput.row].firstName, char);
        }
    };
    $scope.keyboardAction = function (model, char) {
        if(char == 'SPACE'){char = ' '}
        if(char == 'CLEAR'){
            if(model.length > 0){
                model = model.substr(0, model.length -1 );   // fails
            }
        }else{
            model += char; // fails
        }
    };

<button type="button" ng-click="keyboardBtn('SPACE')">SPACE</button>
<button type="button" ng-click="keyboardBtn('Z')">Z</button>
<button type="button" ng-click="keyboardBtn('CLEAR')">CLEAR</button>
J.Olufsen
  • 13,415
  • 44
  • 120
  • 185

1 Answers1

2

Javascript is always pass by value, any changes in a function would not affect the original value. (Please reference this SO).

To achieve what you want, you can pass the object($scope.persons[$scope.focusedInput.row]) instead of the attribute($scope.persons[$scope.focusedInput.row].firstName) and change the attribute value in the function. For example:

$scope.keyboardBtn = function(char){
    if($scope.focusedInput.name == 'inputFirstName'){
        $scope.keyboardAction($scope.persons[$scope.focusedInput.row], char);
    }
};

$scope.keyboardAction = function (model, char) {
    if(char == 'SPACE'){char = ' '}
    if(char == 'CLEAR'){
        if(model.firstName.length > 0){
            model.firstName = model.firstName.substr(0, model.length -1 );
        }
    }else{
        model.firstName += char;
    }
};
Community
  • 1
  • 1
Sibevin Wang
  • 4,480
  • 3
  • 27
  • 27