javascript - Angular - 如何连接变量名称

标签 javascript angularjs variables dynamic concatenation

我刚刚开始学习 Angular,我尝试制作 concat var name,以便我可以动态控制它。

这是我尝试过的 -

<div ng-app="myApp" ng-controller="myCtrl">

<button ng-click="myFunc(1)">Click Me!</button>

<div ng-show="showMe1">
    <h1>Menu:</h1>
    <div>Pizza</div>
    <div>Pasta</div>
    <div>Pesce</div>
</div>

</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.showMe1 = false;
    $scope.myFunc = function(x) {
        var nametocng = 'showMe'+x;
        //var nametocng = $parse("showMe"+x);  // - I tried this also
        $scope.nametocng = !$scope.nametocng;
    }
});
</script>

最佳答案

使用$scope[variable]进行动态。

来自您的评论: 最后,我想制作多个切换,但我想要一个功能用于所有这些切换。然后,每个按钮都会处理一个切换

您可以使用ng-repeat作为按钮来处理不同的菜单

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<button ng-repeat="button in array"  ng-click="myFunc(button)">Click Me!</button>

<div ng-show="showMe1">
    <h1>Menu:</h1>
    <div>Pizza1</div>
    <div>Pasta1</div>
    <div>Pesce1</div>
</div>

<div ng-show="showMe2">
    <h1>Menu:</h1>
    <div>Pizza2</div>
    <div>Pasta2</div>
    <div>Pesce2</div>
</div>
{{nametocng}}

</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.array = [1,2];
    $scope.firstName = "John";
    $scope.lastName = "Doe";
     
    $scope.myFunc = function(x) {
     angular.forEach($scope.array, function(value, key){
       $scope['showMe'+value] = false
});
        var nametocng = 'showMe'+x;
        //var nametocng = $parse("showMe"+x);  // - I tried this also
        $scope[nametocng] = !$scope[nametocng];
    }
});
</script>

</body>
</html>

请运行上面的代码片段

Here is a DEMO

关于javascript - Angular - 如何连接变量名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43086748/

相关文章:

javascript - Angular Controller (按模块)空白页

javascript - 不包含名为

没有取消按钮的Javascript提示框?

javascript - 单击另一个 DIV 时无法将 DIV 获取到 .fadeOut()

javascript - Angularjs 未知提供商错误

javascript - 获取 2 个静态值中的 "the other"的最简单方法是什么?

javascript - 如何从 ng-repeat 所在的同一元素上的另一个指令访问 ng-repeat 的作用域?

angularjs - Angular 中的窗口方向改变事件

python - 将变量从一个 Python 脚本发送到另一个

templates - 如何让 SCons 替换已安装文本文件中的文本