真的希望有人能帮助我解决我最近遇到过几次的问题。
假设我在 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);
}
你也可以使用 $parse
(注入(inject) $parse
)服务。
$scope.getValue = function(exp, row){
return $parse(exp)(row);
}
和
<th ng-repeat="field in fields">{{getValue(field, row)}}</th>
关于javascript - 评估点表示法中的字符串以从 View 中的对象获取相应的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28976326/