如何为两个串联字符串赋值和范围

时间:2018-05-02 08:27:37

标签: javascript angularjs

我的HTML代码: -

<ul class="sub-menu collapse">
     <li ng-hide="abcMenuHide" ng-click="showModal('abcMaster')">
        <a>Add/update listOne</a></li>
     <li ng-hide="xyzMenuHide" ng-click="showModal('xyzMaster')">
        <a>Add/Update listTwo</a></li>
</ul> ... and so on

我试图根据分配给<li>的值隐藏ng-hide元素。 我在这样的指令中创建了这个值: -

$scope.menuListHide = function(){
        for (var group in $scope.data) {
            if (group != "sectionOne") {
                for (var list in $scope.data[group]) { 
                    for (var key in $scope.data[group][list]) { 
                        if ($scope.data[group][list].view != undefined) {
                            if (!$scope.data[group][list].view) {
                                $scope.(list+"MenuHide") = true; \\This assignment is wrong also I am not able to attach scope to it.
                            }
                        }
                        else if($scope.data[group][list][key].view != undefined){
                            if (!$scope.data[group][list][key].view) {
                                $scope.(key+"MenuHide") = true; \\This assignment is wrong also I am not able to attach scope to it.
                            }
                        }
                    }
                }
            }   
        }
    }

$scope.menuListHide();

有什么办法可以为连接字符串分配$scope和值吗?

2 个答案:

答案 0 :(得分:1)

而不是这(语法不正确):

$scope.(list+"MenuHide") = true;

你需要这样做:

$scope[list + "MenuHide"] = true;

要在对象内动态更改属性,需要使用[]包装属性名称并直接在对象上调用它。由于此处$scope是JavaScript对象,因此list + "MenuHide"中的true属性将分配给$scope

答案 1 :(得分:1)

来自MDN Computed property names

  

从ECMAScript 2015开始,对象初始化程序语法还支持计算属性名称。这允许您将一个表达式放在方括号[]中,该表达式将被计算并用作属性名称。

更改$scope.(list+"MenuHide") = true;

list = list + "MenuHide";
$scope[list] = true;

OR:单行$scope[list+ "MenuHide"] = true;