Reputation: 10030
Note: Similar to: angularjs execute expression from variable except I don't want to clutter up my scope with all the possibilities and data sets in use.
I want to be able to utilize pre-determined formulas in Angular's expressions.
Example:
var config = {
"Test": {
name: "test",
formula: true,
formulaValue: "item['propertyOne'] + item['propertyTwo']"
}
}
<div ng-repeat="item in myArray">
<span ng-if="config[item.name].formula">{{config[item.name].formulaValue}}</span>
</div>
Where the formula in formulaValue
gets evaluated as if I typed it like:
<div ng-repeat="item in myArray">
<span>{{item['propertyOne'] + item['propertyTwo']}}</span>
</div>
How would I accomplish this? It's not quite feasible to make a $scope function for each type of formula either, as these are setup in a config in fairly large quantities.
Upvotes: 0
Views: 124
Reputation: 171679
Not the most ideal config setup but worst case you would need to use eval()
which is not well liked due to security
Something like:
function parseConfig(item, configKey){
if(config[configKey].formula){
return eval(config[configKey].formulaValue);
}
}
$scope.parseConfig = parseConfig;
Would put that in a service with your config but for now will just put on scope.
In view would be something like
{{parseConfig(item, 'Test')}}
If it was me I would prefer a config that looked something like
var config = {
"Test": {
name: "test",
formula: true,
formulaType: 'concat',
formulaValue: ['propertyOne','propertyTwo']
}
then you would check formulaType and do what is needed with the properties in the formulaValue without using eval()
Upvotes: 1