【问题标题】:Display a $scope variable using another $scope variable使用另一个 $scope 变量显示一个 $scope 变量
【发布时间】:2020-02-15 05:40:13
【问题描述】:

在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>

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

【问题讨论】:

  • 假设您的 HTML 在 ng-controller 的上下文中,它被分配给包含您的 $scope 变量的同一控制器,这应该只是使用 {{count}}{{published}} 的问题如果您想按字面显示值,请使用您的 HTML。如果您为控制器添加了别名(例如ng-controller="Ctrl as foo"),那么您需要在插值前加上别名(例如{{foo.count}})。
  • 谢谢但我想动态显示值,因为我需要通过 ng-repeat 迭代大约 20 个值,所以只使用 {{count}} 或 {{published}} 不会在我的用例中不起作用。
  • 糟糕,我误读了您的问题。对,在这种情况下,要么将 labels 集合映射到索引 $scope 属性的对象,要么有一个函数返回后者并将其与 ng-repeat 一起使用(例如 ng-repeat="obj in getObjs()")。如果 labels 集合不断变化,则后一种方法可确保您无需显式重新映射标签。

标签: angularjs angularjs-scope angularjs-ng-repeat


【解决方案1】:

使用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>

【讨论】:

    【解决方案2】:

    将您的标签映射到{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>
    

    【讨论】:

    • 感谢您的回答,我认为这也是正确的,但它需要一个额外的地图功能
    猜你喜欢
    • 2015-03-03
    • 1970-01-01
    • 2019-09-29
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 2016-05-16
    • 2016-09-11
    相关资源
    最近更新 更多