我有一个从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
关于angularjs - 在 AngularJs 中设置动态作用域变量 -scope.<some_string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18875486/