Proposal: pluggable parsers #2908
Description
Sometimes, it would be useful to be able to change how an expression is parsed. This would fix a number of problems, such as:
- Enable the possibility of using an accessor function in a ng-model expression. (Allow binding to getter/setter fn #768)
- Evaluate an expression in the parent scope in order to escape an isolate scope (e.g., if you want to use ng-show on the same element as a directive with isolate scope). (Adding ngModel. #2904)
- Enable simpler syntax for specialized use cases, e.g. for i18n.
This could be done by introducing a new concept, which for now I will just call "parser filters". A parser filter is simply a function, which takes a string (the expression to be parsed) as an argument, and returns the parsed expression.
$parse would have to be extended such that it can understand parser filters. I propose a syntax like follows:
<input ng-model="``accessor obj.property($value)">
The _accessor_ part specifies that the expression that follows should be parsed by the "accessor" parser filter. I'm sure others can come up with a better syntax. So $parse would simply pick up the fact that the expression starts with
, then it would read the parser filter name, and pass the rest of the expression (as a string) to the parser filter.
The "accessor" parser filter would be implemented like this:
module.parserFilter('accessor', function($parse) {
return function(expression) {
var result = $parse(expression);
result.assign = function(context, value) {
result(context, {$value: value});
}
return result;
};
});
So, parser filters can be really simple to implement, and in most cases will probably use $parse to do the actual parsing. It would also be reatively simply to implement java-style getProperty/setProperty accessor functions.
There are probably many other use cases for parser filters, they seem to me to be a very flexible feature.