将模型传递给函数时无法更新模型

时间:2014-12-09 14:51:23

标签: angularjs

我正在使用额外的功能来处理键盘输入。似乎值成功传递,但是当我尝试分配这个model += char;值时它会失败。为什么呢?

$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>

1 个答案:

答案 0 :(得分:2)

Javascript始终按值传递,函数中的任何更改都不会影响原始值。 (请参考此SO)。

要实现您想要的效果,您可以传递对象($scope.persons[$scope.focusedInput.row])而不是属性($scope.persons[$scope.focusedInput.row].firstName)并更改函数中的属性值。例如:

$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;
    }
};