问题描述
我有一个从 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?
推荐答案
我发现的解决方案是使用 $parse.
The solution I have found is to use $parse.
将 Angular 表达式转换为函数."
如果有人有更好的答案,请为问题添加一个新答案!
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 中设置动态范围变量 - scope.<some_string>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!