我有一个字符串,我从一个routeParam或一个指令属性或其他什么,我想基于此在范围上创建一个变量.所以:
$scope.<the_string> = "something".
Run Code Online (Sandbox Code Playgroud)
但是,如果字符串包含一个或多个点,我想将其拆分并实际"向下钻取"到范围内.所以'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!
Run Code Online (Sandbox Code Playgroud)
在根据字符串读取变量时,您可以通过执行此操作获得此行为$scope.$eval(the_string),但在分配值时如何执行此操作?
Eri*_*onn 172
我找到的解决方案是使用$ 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
Run Code Online (Sandbox Code Playgroud)
And*_*ray 19
以Erik的答案为出发点.我找到了一个对我有用的简单解决方案.
在我的ng-click功能中,我有:
var the_string = 'lifeMeaning';
if ($scope[the_string] === undefined) {
//Valid in my application for first usage
$scope[the_string] = true;
} else {
$scope[the_string] = !$scope[the_string];
}
//$scope.$apply
Run Code Online (Sandbox Code Playgroud)
我已经使用和不使用$ scope进行了测试.$ apply.没有它正确工作!
Dem*_*ave 13
从结果中创建动态角度变量
angular.forEach(results, function (value, key) {
if (key != null) {
$parse(key).assign($scope, value);
}
});
Run Code Online (Sandbox Code Playgroud)
PS.不要忘记将$ parse属性传递给控制器的函数
小智 5
如果您可以使用Lodash,可以使用_.set()在一行中执行您想要的操作:
_.set(object,path,value)设置对象上path的属性值.如果路径的一部分不存在则创建它.
所以你的例子就是: _.set($scope, the_string, something);
| 归档时间: |
|
| 查看次数: |
119003 次 |
| 最近记录: |