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

标签 javascript angularjs

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

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

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

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

最佳答案

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

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

关于javascript - 使用 HTML 中的字符串访问范围键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26992484/

相关文章:

javascript - Angular-CLI 错误 : Return type of public method from exported class has or is using name 'ErrorObservable' from external module but cannot be named

javascript - Angularjs 动态对象更新

html - 我将与 ng-include 一起使用什么文件路径?

javascript - 如何处理调用同一函数的多个 Ajax 调用?

javascript - AngularJS 绑定(bind)对象

javascript - 使用 Objective-C 从 HTML 中获取由 javascript 生成的表

javascript - 替代 eval() 以使用 LiveValidation 构造函数

javascript - Backbone.js 中的登录处理

javascript - 如何将 Angular 图表与我的信息结合使用?

javascript - AngularJS $http.delete 破坏了 "TypeError: Cannot assign to read only property ' 方法’..”