我有一个字符串,我从一个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