gpt4 book ai didi

javascript - 你能用 $parse 推送到 Angular 中动态声明的数组吗?

转载 作者:行者123 更新时间:2023-11-30 10:00:45 24 4
gpt4 key购买 nike

我想在 angularJS 中使用 $parse 来动态创建一个引用数组的范围变量,然后 push 到该数组;但是 $parseassign 方法似乎并不能解决问题。

$scope.life.meaning = [];

var the_string = 'life.meaning';

// Get the model
var model = $parse(the_string);

想要将“42”压入数组。所以以下将不起作用:

// Assigns a value to it
model.assign($scope, 42);

还有其他方法吗?谢谢。

最佳答案

您的示例正在覆盖范围内该对象的分配。 $parse 可用于获取或进行分配。您需要做的是获取数组,然后将项目推送到您获得的数组中。因为 JavaScript 数组是内存中的指针,所以添加到您检索到的数组就可以了。

//get the current value as evaluated against the $scope
var ar = $parse('life.meaning')($scope);

//if the value isn't an array then make it one
if (!Array.isArray(ar)) {
ar = [];
$parse('life.meaning').assign($scope, ar);
}

//add an item to the array
ar.push(42);

关于javascript - 你能用 $parse 推送到 Angular 中动态声明的数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31841025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com