Search code examples
angularjsangularjs-scopeangularjs-ng-repeat

Display a $scope variable using another $scope variable


Display a scope variable which is similar to ng-repeat element in Angularjs

These are my scope variables

$scope.published = true;
$scope.count = 3;

I also have an array called labels

$scope.labels = ['published', 'count'];

In the view I want to view these data as the label name - label value.

<div ng-repeat="label in labels">
    {{label}} -  {{Here I want the value from the Scope variable}}
</div>

Can someone help me how to access the scope variable in this kind of scenario?


Solution

  • Use the this identifier and bracket notation property accessors:

    <div ng-repeat="label in labels">
        {{label}} -  {{this[label]}}
    </div>
    

    From the Docs:

    It is possible to access the context object using the identifier this and the locals object using the identifier $locals.

    For more information, see

    The DEMO

    angular.module("app",[])
    .controller("ctrl", function($scope) {
        $scope.published = true;
        $scope.count = 3;
        $scope.labels = ['published', 'count'];
    })
    <script src="//unpkg.com/angular/angular.js"></script>
    <body ng-app="app" ng-controller="ctrl">
        <div ng-repeat="label in labels">
            {{label}} -  {{this[label]}}
        </div>
    </body>