Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why scope value can't be changed from HTML by using "switch" technique?

I have simple controller code:

JS

$scope.showErrorAlert = false;


$scope.switchBool = function(value) {
    value = !value;
};

HTML

<div class="alert alert-error" ng-show="showErrorAlert">
                <button type="button" class="close" data-ng-click="switchBool(showErrorAlert)" >×</button>
              <strong>Error!</strong> {{errorTextAlert}}
             </div>

From snippets of code you can see that I try to change $scope.showErrorAlert value.

However it doesn't work, value changes but not showErrorAlert.

Can anybody tell me why and how to make it work, please?

Thank you

like image 827
Maxim Shoustin Avatar asked Jun 30 '13 12:06

Maxim Shoustin


1 Answers

JS passes parameters by value. A simple substitute for pass by reference is to pass an object (as opposed to the property itself).

I.e.

$scope.showErrorAlert = { value: false };

$scope.switchBool = function(obj) {
    obj.value = !obj.value;
};

Or you might refactor the switchBool code to operate on $scope itself. You need to hardcode or abstract "showErrorAlert" then, tough. Depends on your requirements.

like image 101
zany Avatar answered Sep 28 '22 05:09

zany