在AngularJs设置动态范围的变量 - 范围&LT; some_string&GT; [英] Setting dynamic scope variables in AngularJs - scope.<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!
在阅读基于字符串的变量,你可以得到这样做 $范围。$的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.
恩角pression转换成一个功能。
"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屋!