Pass $scope variable to function by reference

穿精又带淫゛_ 提交于 2019-12-11 02:34: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:


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



来源:https://stackoverflow.com/questions/28235514/pass-scope-variable-to-function-by-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!