我想在HTML模板中使用一个有点深度的JSON对象。
{
"service": {
"name": "example",
"url": "abc.com",
"template": "/abc/def/v1",
"metadata": {
"password": "dontguessme",
"username": "supereasy"
}
}
}
我包含一个包含以下HTML代码的模板。
<div class="modal-body" ng-include="service.instructionsTemplate"> </div>
在模板中有以下内容。
<h1>Some example content</h1>
{{service.metadata.password}}
我的问题是,而不是通过service.metadata引用字段密码,有没有办法只用变量密码引用它。
我试图通过围绕作用域和模板的一些Angular文档进行深入研究,但却出现了空洞。我看到你可以使用ng-init。
我能够使用ng-init="metadata = service.metadata"
并且能够通过metadata.password
在模板中引用字段密码。
但是我想通过password
引用它。
有什么想法吗?
答案 0 :(得分:0)
您已经ng-init="metadata = service.metadata"
了,为什么不进一步做ng-init="password = service.metadata.password"
?
另一种方法是将$scope.password = service.metadata.password
绑定在您在该页面上使用的控制器内
编辑: OP提出了更通用的解决方案
如果您不知道属性名称,那么最好的方法是绑定元数据对象,就像您已经做的那样,然后使用ng-repeat
在您的控制器中:
$scope.metadata = service.metadata
在你的模板(视图)中:
<h1>Some example content</h1>
<ul>
<li ng-repeat="element in metadata">{{element}}</li>
</ul>
答案 1 :(得分:0)
您可以轻松地将密码设置为控制器内部的内容:
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.data = {
"service": {
"name": "example",
"url": "abc.com",
"template": "/abc/def/v1",
"metadata": {
"password": "dontguessme",
"username": "supereasy"
}
}
};
$scope.password = $scope.data.service.metadata.password;
});