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