通过引用将$ scope变量传递给函数

时间:2015-01-30 12:02:38

标签: javascript angularjs angularjs-scope

我一直在尝试实现一个带有范围变量的函数,并改变它的原始但没有运气。

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

为了展示我想要实现的目标,我创建了这个Plunker:http://plnkr.co/edit/kEq8YPJyeAfUzuz4Qiyh?p=preview

我期望点击button1或button2,var1或var2将更改为'已更改'。这甚至可能吗?

1 个答案:

答案 0 :(得分:4)

不是你描述的方式,但是你可以传递一个带有变量名的字符串并使用它来指向右边的字符串:

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

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

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

更新示例:http://plnkr.co/edit/K4tnhFdQ7KsuNtKTRI2X?p=preview

或者,另一种方法是将函数传递给changeVar方法:

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

在此处查看:http://plnkr.co/edit/ttRWUDzD9jAEj2Z7O64k?p=preview