最佳答案
我有一个字符串,我已经从 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)
来获得这种行为,但是在赋值时如何执行呢?