通过引用将 $scope 变量传递给函数 [英] Pass $scope variable to function by reference

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

问题描述

我一直在尝试实现采用范围变量并更改其原始值的函数,但没有成功.

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=preview

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

我期望点击 button1 或 button2、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

这篇关于通过引用将 $scope 变量传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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