通过$范围的变量参考作用 [英] Pass $scope variable to function by reference

查看:89
本文介绍了通过$范围的变量参考作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力实现函数,该函数范围的变量,并改变它的原始,但没有运气。

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

要证明什么,我想实现我创造了这个Plunker:的http:/ /plnkr.co/edit/kEq8YPJyeAfUzuz4Qiyh?p=$p$pview

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

我想到的是,无论是在Button1的或按钮2,VAR1和VAR2点击将被更改为改变。这甚至可能?

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

推荐答案

不要在你所描述的方式,但你可以传递一个字符串变量名称,并用它来指向正确的:

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

更新例如: http://plnkr.co/edit/K4tnhFdQ7KsuNtKTRI2X?p= preVIEW

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

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

请参阅这里: http://plnkr.co/edit/ttRWUDzD9jAEj2Z7O64k?p = preVIEW

这篇关于通过$范围的变量参考作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆