2

I have been trying to implement function that takes scope variable and changes it's original but with no luck.

 var app = angular.module('plunker', []);    
 app.controller('MainCtrl', function($scope) {
  $scope.var1 = 1;
  $scope.var2 = 2;

  $scope.changeVar = function (varX) {
    varX = 'changed';
  }

  $scope.changeVar1 = function () {
    $scope.changeVar($scope.var1);
  };

  $scope.changeVar2 = function () {
    $scope.changeVar($scope.var2);
  }
});

To demonstrate what I am trying to achieve I have created this Plunker: http://plnkr.co/edit/kEq8YPJyeAfUzuz4Qiyh?p=preview

What I expect is that either clicking on button1 or button2, var1 or var2 will be changed to 'changed'. Is this even possible?

1 Answer 1

4

Not in the way you describe, but you could pass a string with the variable name and use that to point to the right one:

 $scope.changeVar = function (varX) {
    $scope[varX] = 'changed';
  }

  $scope.changeVar1 = function () {
    $scope.changeVar("var1");
  };

  $scope.changeVar2 = function () {
    $scope.changeVar("var2");
  }

Updated example: http://plnkr.co/edit/K4tnhFdQ7KsuNtKTRI2X?p=preview

Or, another way would be to pass a function to your changeVar method:

$scope.changeVar = function (varX) {
    varX('changed');
  }

  $scope.changeVar1 = function () {
    $scope.changeVar(function(x){ $scope.var1 = x });
  };

  $scope.changeVar2 = function () {
    $scope.changeVar(function(x){ $scope.var2 = x });
  }

See that here: http://plnkr.co/edit/ttRWUDzD9jAEj2Z7O64k?p=preview

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.