javascript - 评估点表示法中的字符串以从 View 中的对象获取相应的值

标签 javascript angularjs

真的希望有人能帮助我解决我最近遇到过几次的问题。

假设我在 AngularJS 中有两个对象。

$scope.fields = ['info.name', 'info.category', 'rate.health']

$scope.rows = [{
    info: { name: "Apple", category: "Fruit"},
    rate: { health: 100, ignored: true}
},{
    info: { name: "Orange", category: "Fruit"},
    rate: { health: 100, ignored: true}
},{
    info: { name: "Snickers", category: "Sweet"},
    rate: { health: 0, ignored: true}
}]

然后我想在 View 中显示一个表格,该表格仅显示 $scope.fields 中的字段。如果表格是扁平的,这将非常容易,而且我知道我可以使用 JavaScript 将其扁平化,但必须有一种方法可以通过将点符号转换为路径来实现这一点。

我添加了一个 JSFiddle 来演示我遇到的问题:

JSFiddle:http://jsfiddle.net/7dyqw4ve/1/

我也尝试过按照下面的建议做一些事情,但问题是在 View 中使用函数的糟糕做法: Convert JavaScript string in dot notation into an object reference

如果有人有任何想法,我将不胜感激。

最佳答案

在这种情况下,您可以使用通过属性 $eval 公开的angular 内置求值器。 在范围 ( not the vanilla eval ) 上评估任何 Angular 表达式(不像 eval 那样评估 javascript)。 Angular 在解析绑定(bind)时在内部使用它来评估作用域上的表达式。

例子:-

{{$eval(field, row)}}

你可以这样做:-

 <th ng-repeat="field in fields">{{$eval(field, row)}}</th>

或者将逻辑包装在 Controller 中并通过作用域上的方法公开它。

  <th ng-repeat="field in fields">{{getValue(field, row)}}</th>

$scope.getValue = function(exp, row){
    return $scope.$eval(exp, row);
}

Demo

你也可以使用 $parse (注入(inject) $parse)服务。

$scope.getValue = function(exp, row){
    return $parse(exp)(row);
}

<th ng-repeat="field in fields">{{getValue(field, row)}}</th>

Demo

关于javascript - 评估点表示法中的字符串以从 View 中的对象获取相应的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28976326/

相关文章:

javascript - 在 Angular JS 中使用 HTML 版本控制渲染动态 UI

javascript - Chrome 和 Firefox POST 调用的内容类型差异

javascript - angularjs 获取所选 ng-repeat 选项的另一个属性以传递到另一个模型中

javascript - 自动滚动到“下一页”的顶部

javascript - 在开发阶段,应用程序在 Tablet rotate 上崩溃

javascript - 将 json 字符串转换为适合 esri.geometry.Multipoint 的字符串

javascript - 这对 JavaScript 函数有何不同?

javascript - jQuery 通过 ID 引用外部模板脚本

javascript - Onsen UI滑动菜单

javascript - Angular JS - 使服务可以从 Controller 和 View 全局访问