在 AngularJs 中设置动态范围变量 - 范围.<some_string> [英] Setting dynamic scope variables in AngularJs - scope.<some_string>

查看:8
本文介绍了在 AngularJs 中设置动态范围变量 - 范围.<some_string>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从 routeParam 或指令属性或其他任何东西获得的字符串,我想基于此在范围上创建一个变量.所以:

I have a string I have gotten from a routeParam or a directive attribute or whatever, and I want to create a variable on the scope based on this. So:

$scope.<the_string> = "something".

但是,如果字符串包含一个或多个点,我想将其拆分并实际向下钻取"到范围内.所以 'foo.bar' 应该变成 $scope.foo.bar.这意味着简单的版本将无法工作!

However, if the string contains one or more dots I want to split it and actually "drill down" into the scope. So 'foo.bar' should become $scope.foo.bar. This means that the simple version won't work!

// 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) 来获得此行为,但是在赋值时如何执行呢?

When reading a variable based on a string you can get this behavior by doing $scope.$eval(the_string), but how to do it when assigning a value?

推荐答案

我找到的解决方案是使用 $解析.

The solution I have found is to use $parse.

将 Angular 表达式转换为函数."

"Converts Angular expression into a function."

如果有人有更好的答案,请为问题添加新答案!

If anyone has a better one please add a new answer to the question!

示例如下:

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

这篇关于在 AngularJs 中设置动态范围变量 - 范围.&lt;some_string&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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