我有一个 Angular 应用程序,其中数据通过 JSON 文件加载。对于各种对象,属性之一是“描述”。在我的应用程序中,我通过 {{item.Description}}
将其弹出到我的 html 中。我的问题是 JSON 文件中的字符串具有需要根据变量进行调整的值。例如,“值为 160(每个变量+20)”。我希望此描述读出 160 加 20 倍所提供变量的值。
不幸的是,我不能只将 {{160+(20*var)}}
放入描述中,因为它只是将表达式打印为字符串。
是否有办法以 Angular 创建该绑定(bind),以便它根据其他变量动态更新?
更新 根据请求,我将添加尽可能多的代码。
在我的文件头中,我包含一个 JSON 文件:
<script src="path/to/file.json"></script>
然后,我就有了我的 Controller :
app.controller('itemController', function(){
this.items = Items //Items is declared in the JSON file as the JSON object.
});
然后在我的 HTML 中调用:
<div ng-controller="itemController as ctrl">
<span class="description" ng-repeat="item in ctrl.items">
{{item.Description}}
</span>
</div>
问题是,item.Description
有我想要评估的表达式。我通常只会执行 {{160+(20*ctrl.var)}}
,但由于该表达式包含在 item.Description
字符串中,Angular 不会正常评估即可。
最佳答案
看来您可以通过将 {{item.Description}}
替换为 {{$eval(item.Description)}}
来实现此目的,这将评估字符串作为 Angular 表达式。请参阅Angular docs for expressions ,或a StackOverflow post about $eval .
编辑: OP 已澄清 item.Description
可能包含混合的 Angular 表达式和其他文本,例如 “该值为 {{85 + 22 * ctrl.var}}"
。幸运的是the Angular docs for $compile包含一个解决这个问题的例子!这是一个简短的演示。
angular.module('app', [])
.directive('compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
})
.controller('itemController', function() {
this.var = 5;
this.items = [
{Description: "What's 1+1? It's {{1+1}}"},
{Description: "The value is {{85+22*ctrl.var}}"},
{Description: "He{{'llo'}} World!"}
];
});
body {
font-family: sans-serif;
}
#main > span {
background-color: #ddd;
padding: 8px 16px;
margin: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app" class="ng-scope">
<h1>Compile Test!</h1>
<div ng-controller="itemController as ctrl" id="main">
<span class="description ng-scope" ng-repeat="item in ctrl.items" compile="item.Description"></span>
</div>
</body>
关于javascript - 评估 JSON 文件中的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30009461/