使用 HTML 中的字符串访问范围键

Accessing scope keys with string in HTML

本文关键字:访问 范围 字符串 HTML 使用      更新时间:2023-09-26

我想显示服务器通过websocket动态创建和更新的按钮列表。我的范围如下所示:

$scope = {
  buttons: ["buttonA", "buttonB"],
  buttonA: { caption: "OK" },
  buttonB: { caption: "Cancel" }
};

在我的 HTML 中,我将使用 ng-repeat 来浏览按钮列表,将它们添加到 DOM 并使用每个按钮的 caption 属性用作"value"属性。

但是我不知道如何从 HTML 中的字符串访问 json 字段。

我不确定你为什么想要这样的模型。您可以像这样维护 $scope.button 中的按钮:

<div ng-app="myApp" ng-controller="MyCtrl">
    <div ng-repeat="b in buttons">
        <button>{{b.caption}}</button>
    </div>
</div>
<script>
var app = angular.module("myApp", []);
app.controller("MyCtrl",function ($scope) {
    $scope.buttons = [{ caption: "OK" }, { caption: "Cancel" }];
});
</script>

如果出于某种原因,您希望将各个按钮放在作用域的"根"上,则可以使用如下所示的查找函数:

<div ng-app="myApp" ng-controller="MyCtrl">
    <div ng-repeat="b in buttons">
        <button>{{lookup(b).caption}}</button>
    </div>
</div>
<script>
var app = angular.module("myApp", []);
app.controller("MyCtrl",function ($scope) {
    $scope.buttons =  ["buttonA", "buttonB"];
    $scope.buttonA = { caption: "OK" };
    $scope.buttonB = { caption: "Cancel" };
    $scope.lookup = function(key) {
        return $scope[key];
    }
});
</script>