Angular - how to concatenate var name

advertisements

I just started to learn Angular, and I tried to make concat var name so I can control it dynamically.

This is what I tried -

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


use $scope[variable] for dynamic.

From your comment: In the end, I want to make multiple Toggles, but I want one function for all of them. and then, every button will handle one toggle

You can use ng-repeat for button to handle different menu's

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

Please run the above snippet

Here is a DEMO