.directive('ngCalculator', function($compile, $timeout){ return { restrict: 'EA', require: 'ngModel', scope: { devices: '=', key: '=', displayName: '=', bindAttr: '=' }, link: function(scope, element, attrs, ngModel) { scope.results = {}; var text = attrs.ngCalculator; var replacements = text.match(/\[[a-zA-Z0-9]+\]/g); var formula = text.match(/\<\-(.+)\-\>/); text = text.replace(formula[0], ''); for(var i = 0; i < replacements.length; i++) { var id = replacements[i].replace('[','').replace(']',''); text = text.replace(replacements[i], ' '); } text = ''+text+''; element.replaceWith($compile(text)(scope)); scope.$watchCollection('results', function() { var input_check = true; angular.forEach(replacements, function(replacement) { var id = replacement.replace('[','').replace(']',''); var modelValue = parseInt(scope.results[id]); if(!modelValue) { input_check = false; } }); if(input_check == true){ var formula_instance = formula[1]; angular.forEach(replacements, function(replacement) { var id = replacement.replace('[','').replace(']',''); var regex = new RegExp(id, "g"); formula_instance = formula_instance.replace(regex, scope.results[id]); }); ngModel.$setViewValue(scope.$eval(formula_instance)); ngModel.$render(); } }); } }})
这是一个自定义计算器的指令,用来解析一串字符,效果图如下:
能处理穿插在自然语言里计算公式.
使用方法:
其实sample字符串是生成表单的,[n]这个是变量替换,将变量替换成 input[type="text"],
<-a*b*0.01+c*d*0.01*12+e+f+g->
这是变量拼凑起来的计算公式,
ngModel的result返回计算结果。