使用另一个$ scope变量显示$ scope变量

问题描述 投票:2回答:2

显示一个类似于Angularjs中ng-repeat元素的作用域变量

这些是我的范围变量

$scope.published = true;
$scope.count = 3;

我也有一个称为标签的数组

$scope.labels = ['published', 'count'];

在视图中,我想以标签名称-标签值的形式查看这些数据。

<div ng-repeat="label in labels">
    {{label}} -  {{Here I want the value from the Scope variable}}
</div>

有人可以帮助我在这种情况下如何访问范围变量吗?

angularjs angularjs-scope angularjs-ng-repeat
2个回答
4
投票

使用this标识符和bracket notation property accessors

<div ng-repeat="label in labels">
    {{label}} -  {{this[label]}}
</div>

来自文档:

可以使用标识符this访问上下文对象,并使用标识符$locals访问本地对象。

有关更多信息,请参阅

演示

angular.module("app",[])
.controller("ctrl", function($scope) {
    $scope.published = true;
    $scope.count = 3;
    $scope.labels = ['published', 'count'];
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
    <div ng-repeat="label in labels">
        {{label}} -  {{this[label]}}
    </div>
</body>

1
投票

将标签映射到{key:"labelKey", value:"valueInScope"},以便可以在模板中使用它们。

类似的事情可能起作用

labels = ['published','count']
         .map(
             function(label){
                return {key:label,value:$scope[label]}
             }); 

然后使用

<div ng-repeat="label in labels">
   {{label.key}} - {{label.value}}
</div>
© www.soinside.com 2019 - 2024. All rights reserved.