javascript - Replace variables from the mathematical equation with array values using angularjs? -
i have equation following format
$(5)+$(6) 5 & 6 input ids.
each input id has @ least 100 values array. format follows
var data = [{id : 5, inputs :[{value:10},{value:10},{value:11},...,{value:12}]},{id : 6, inputs :[{value:10},{value:10},{value:11},...,{value:12}]}];
what want replace equation variables corresponding values data.
following current code
//tpl $(5)+$(6); $scope.value_replacer = function (tpl, data) { var re = /\$\(([^\)]+)?\)/g, match; var valuearray = []; (var = 0; < data.length; i++) { while (match = re.exec(tpl)) { if (match[1] == data[i].id) { (var j = 0; j < data[i].inputs.length; j++) { tpl = tpl.replace(match[0], data[i].inputs[j].value); if (i == data.length - 1) { valuearray.push(tpl); } } re.lastindex = 0; } } } return valuearray; }
if have 100 data values , resulting array should contain 100 values. getting same values. please me correct values?
update
my equation user defined ie equation may time $(5) - $(6) or $(5)*$(6) that.. want replace 5 , 6 (ie ids)
you can use 2 loops achieve this
var myapp = angular.module('myapp', []); myapp.controller('ctrl', ['$scope', function($scope) { $scope.data = [{ id: 5, inputs: [{ value: 10 }, { value: 10 }, { value: 11 }, { value: 12 }] }, { id: 6, inputs: [{ value: 10 }, { value: 10 }, { value: 8 }, { value: 12 }] }]; (var = 0; < $scope.data.length; i++) { sum = 0 (var j = 0; j < $scope.data[i].inputs.length; j++) { sum += $scope.data[i].inputs[j].value; } $scope.data[i].sum = sum; } $scope.findind=function(id){ var index = $scope.data.findindex(x=>x.id === id); return index; } $scope.multiply=function(){ var res = 1; (var = 0; < arguments.length; i++) { var idsum=$scope.findind(arguments[i]); res *= parseint($scope.data[idsum].sum); } return res; } $scope.divide=function(){ var res =$scope.data[$scope.findind(arguments[0])].sum; (var = 1; < arguments.length; i++) { var idsum=$scope.findind(arguments[i]); res /= parseint($scope.data[idsum].sum); } return res; } $scope.add=function(){ var res = 0; (var = 0; < arguments.length; i++) { var idsum=$scope.findind(arguments[i]); res += parseint($scope.data[idsum].sum); } return res; } $scope.subtract=function(){ var res = 0; (var = 0; < arguments.length; i++) { var idsum=$scope.findind(arguments[i]); res = parseint($scope.data[idsum].sum)-res; } return res; } console.log($scope.add(5,6)); console.log($scope.subtract(5,6)); console.log($scope.multiply(5,6)); console.log($scope.divide(5,6)); }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myapp" ng-controller="ctrl"> </div>
Comments
Post a Comment