Pass $scope variable to function by reference

2019-07-19 16:37发布

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条回答
SAY GOODBYE
2楼-- · 2019-07-19 17:04

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

查看更多
登录 后发表回答