Anita Patil
Anita Patil

Reputation: 27

How to Display value of dynamically created varible using AngularJS

My HTML template code is:

<p>{{"fieldname_"+lang}}</p>

In the controller I have the following:

$scope.lang = "mr";
$scope.fieldname_mr = "Dynamic varible";

I want the result to be Dynamic varible, but it is fieldname_mr.

How can I achieve that?

Upvotes: 1

Views: 50

Answers (3)

Pradip Talaviya
Pradip Talaviya

Reputation: 409

Yes you can do it like you set your dynamic variable in angular as follow:

what you want variable name store in variable than follow code:

$scope[dynamic_var]=Value of variable;

when you fetch this value as like:

Use this when you not fix property of scope alert($scope[dynamic_var]) use when you have fix property name alert($scope.dynamic_var)

Upvotes: 0

&#193;lvaro Touz&#243;n
&#193;lvaro Touz&#243;n

Reputation: 1230

that you wnt is not able, i made a middleware solution that mantains all your needed but passed by a function that made the return of var, understand that angular force to made like this

<div ng-controller="MyCtrl">
  <span ng-init="">{{getValue('fieldname_'+lang)}}</span>
</div>

var myApp = angular.module('myApp',[]);



function MyCtrl($scope) {
    $scope.lang = "mr"; $scope.fieldname_mr = "Dynamic varible";
    $scope.getValue =function(name){
        return $scope[name] ||'no existe man';
    }
}

Upvotes: 0

Stanislav Kvitash
Stanislav Kvitash

Reputation: 4622

You can use bracket notation to achieve this:

angular.module('app', [])
.controller('testController',
  function testController($scope) {
   $scope.lang = "mr";   
   $scope.dynamicVars = {fieldname_mr : "Dynamic varible"};

});
<body ng-app="app">
<div class="table-responsive" ng-controller="testController">
    {{dynamicVars["fieldname_" + lang]}}
</div>
</body>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

Upvotes: 2

Related Questions