AngularJS更新数组变量和非数组变量,其名称是通过字符串获取的 [英] AngularJS update array var and non-array var whose names were obtained by string

查看:95
本文介绍了AngularJS更新数组变量和非数组变量,其名称是通过字符串获取的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新以字符串形式获取的不同变量。有些是数组,有些则不是。为了通过相同的函数更新这些值,我需要通过字符串来获取它们。以下代码仅适用于非数组变量。

I'm trying to update different variables that are obtained as strings. Some are arrays, and some are not. For these values to be updated by the same function, I'd need for them to be obtained by a string. The following code only works with non-array variables.

HTML:

Message is: {{ message }}
<button ng-click="updateVar('message')">Update</button>
<br>
Message in array is: {{ messages.welcome }}
<button ng-click="updateVar('messages.welcome')">Update</button>

AngularJS:

AngularJS:

$scope.message = 'Simple message';

$scope.messages = {
    welcome: 'Message in array'
};

$scope.updateVar = function(varToUpdate) {
    $scope[varToUpdate] = 'Var was updated!';
};

如何使用数组?

谢谢!

推荐答案

您可以将显示的变量用作参数:

You can use the displayed variable as a parameter:

Message is: {{ message }}
<button ng-click="updateVar(message)">Update</button>
<p>
Message in array is: {{ messages.welcome }}
<button ng-click="updateVar(messages.welcome)">Update</button>

&在您的js文件中:

& in your js file:

$scope.message = 'Simple message';

$scope.messages = {
    welcome: 'Message in array'
};

$scope.updateVar = function(varToUpdate) {
     $scope[varToUpdate] = 'Var was updated!';
};

这篇关于AngularJS更新数组变量和非数组变量,其名称是通过字符串获取的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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