一尘不染

在AngularJs中设置动态范围变量-范围。

angularjs

我有一个从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),但是在分配值时如何实现呢?


阅读 249

收藏
2020-07-04

共1个答案

一尘不染

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

“将Angular表达式转换为函数。”

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

这是示例:

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
2020-07-04