在AngularJs中设置动态范围变量 - 范围.<some_string>

Eri*_*onn 96 scope angularjs

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

  • 谢谢你的回答.我想指出,assign也适用于复杂的对象,而不仅仅是原始类型. (3认同)

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.没有它正确工作!

  • 请注意,这与问题的完全不同.该问题的目标是基于字符串创建具有多于1个深度的动态范围变量.所以要创建"scope.life.meaning"而不是"scope.lifeMeaning".使用$ scope [the_string]不会那样做.对于你的具体情况,请记住!在javascrip中,undefined实际上是正确的,所以你实际上可以跳过整个if语句,只做$ scope [the_string] =!$ scope [the_string] ;. 可能会稍微混淆代码,所以我不确定它是否真的是你想要的东西. (13认同)

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的属性值.如果路径的一部分不存在则创建它.

https://lodash.com/docs#set

所以你的例子就是: _.set($scope, the_string, something);