angularjs - How dynamically get the value of a JSON variable in Angular? -
hi want this:
{{item.price.{{comparator}}}}
i mean, take value type of price using {{comparator}} variable.
this example of code (the data bigger , have more types of prices):
var items = [ {"name":"item1",price:{public:10,private:15,other1:16.3,other2:17.5}}, {"name":"item2",price:{public:20,private:45}}, ] var angularapp = angular.module('angularapp', [ 'angularappcontrollers', ]); var angularappcontrollers = angular.module('angularappcontrollers', []); angularappcontrollers.controller('comparationctrl', ['$scope', function ($scope) { $scope.comparator = "private"; $scope.data = items; } ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div ng-app="angularapp"> <div ng-controller="comparationctrl"> <select ng-model="comparator"> <option value="public">public</option> <option value="private">private</option> <option value="other1">other 1</option> <option value="other2">other 2</option> <option value="othern">....</option> </select> {{comparator}} <br /> <ul> <li ng-repeat="item in data"> {{item.name}} - {{item.price.public}} - <strong>(item.price.{{comparator}})</strong> </li> </ul> </div> </div>
like this: https://plnkr.co/edit/irhejrhz8eofb5lmtx7x
angular.module('app', []) .config(function() { }) .controller('ctrl', function($scope) { $scope.obj = { "name": "item1", "price": { "public": "10", "private": "15", "other1": "16.3", "other2": "17.5" } }; $scope.prop = 'public'; });
and html:
<!doctype html> <html ng-app="app"> <head> <script src="https://code.angularjs.org/1.5.8/angular.js"></script> <link rel="stylesheet" href="style.css"> </head> <body ng-controller="ctrl"> <pre>{{obj.price[prop]|json}}</pre> <script src="script.js"></script> </body> </html>
basically, {{obj[apropertydefinedinscope]}}
Comments
Post a Comment