加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在AngularJs – scope中设置动态范围变量

发布时间:2020-12-17 09:09:16 所属栏目:安全 来源:网络整理
导读:我有一个字符串,我从一个routeParam或一个指令属性或任何东西,我想在范围基于此创建一个变量。所以: $scope.the_string = "something". 但是,如果字符串包含一个或多个点,我想要拆分它,实际上“向下钻
我有一个字符串,我从一个routeParam或一个指令属性或任何东西,我想在范围基于此创建一个变量。所以:
$scope.<the_string> = "something".

但是,如果字符串包含一个或多个点,我想要拆分它,实际上“向下钻取”到范围。所以’foo.bar’应该变成$ scope.foo.bar。这意味着简单的版本不会工作!

// This will not work as assigning variables like this will not "drill down"
// It will assign to a variables named the exact string,dots and all.
var the_string = 'life.meaning';
$scope[the_string] = 42;
console.log($scope.life.meaning);  // <-- Nope! This is undefined.
console.log($scope['life.meaning']);  // <-- It is in here instead!

当读取一个基于字符串的变量时,你可以通过$ scope。$ eval(the_string)来获得这个行为,但是在赋值时如何做呢?

我发现的解决方案是使用 $parse。

“Converts Angular expression into a function.”

如果任何人有更好的一个,请添加一个新的答案的问题!

这里是例子:

var the_string = 'life.meaning';

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

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

// Apply it to the scope
// $scope.$apply(); <- According to comments,this is no longer needed

console.log($scope.life.meaning);  // logs 42

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读