I want to have a simple input field where you can type in a javascript expression, and have it be eval-ed on entry, kind of like a poor-man's calculator.
So far, what I have sort of works.. but now I want to decorate it with css classes when the expression itself is invalid. Can someone suggest a way to do it?
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script>
function Ctl($scope) {
$scope.expr = '1+1';
}
angular.module('filters', []).
filter('evaluate', function() {
return function(input) {
try {
return eval(input);
} catch (e) {
return input;
}
};
});
angular.module('main', ['filters']);</script>
<head>
<body ng-controller="Ctl" ng-app="main">
<div><input type="text" ng-model="expr"></div>
<span>{{expr|evaluate}}</span>
</body>
Using the suggestion offered by Manny D, I modified the code to look as follows, and all seems well. There is a caution in how to pass param to a filter function in angular js about not using the 'this' param directly, but I think I'm ok here, doing that.. Anyone care to comment?
<head>
<style type="text/css">
.red {background-color: #fee;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script>
function Ctl($scope) {
$scope.cls = 'green';
$scope.expr = '1+1';
}
angular.module('filters', []).
filter('evaluate', function() {
return function(input, a1, a2) {
try {
this.cls = 'green';
return res = eval(input);
} catch (e) {
this.cls = 'red';
return input;
}
};
});
angular.module('main', ['filters']); // declare dependencies</script>
<head>
<body ng-controller="Ctl" ng-app="main">
<div><input type="text" ng-class="cls" ng-model="expr"></div>
<span>{{expr|evaluate}}</span>
</body>