angularjs - 在 AngularJs 中设置动态作用域变量 -scope.<some_string>

标签 angularjs scope continuous-integration

我有一个从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

关于angularjs - 在 AngularJs 中设置动态作用域变量 -scope.<some_string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18875486/

相关文章:

javascript - 尝试创建大量变量和 for 循环是行不通的

javascript - jquery在ajax中调用函数时this指针作用域

Jenkins 操作日志

apache - 使用 Jenkins 或 Phing 重新启动 apache

javascript - AngularJS 不用 JQuery 获取元素属性

javascript - 未定义的 ng-bind 是否比 ng-bind 和 ng-show 更昂贵?

javascript - Angularjs 按钮在 ng-repeat 中加载状态指令

powershell - 设置位置范围

ssh - 如何通过 SSH 调试 CircleCI VM?

javascript - While 循环在 angularjs 中无法正常工作