Reputation: 65278
I have the code for the ngList directive that AngularJS developed. I would like to implement something similar to it but i don't understand parts of the code. Here is the code
var ngListDirective = function() {
return {
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
var match = /\/(.*)\//.exec(attr.ngList),
separator = match && new RegExp(match[1]) || attr.ngList || ',';
var parse = function(viewValue) {
var list = [];
if (viewValue) {
forEach(viewValue.split(separator), function(value) {
if (value) list.push(trim(value));
});
}
return list;
};
ctrl.$parsers.push(parse);
ctrl.$formatters.push(function(value) {
if (isArray(value)) {
return value.join(', ');
}
return undefined;
});
}
};
};
Here are the parts I do not understand:
Upvotes: 4
Views: 610
Reputation: 24676
First, kudos for reading source!
ctrl
is the controller(s) of the required directive(s) (in this case coming from the ngModel
found in require:
)
$parsers and $formatters- http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController
In short, and keeping in mind that Angular has to track both the DOM representation of ngModel
data as well as the Angular model's representation, $parsers handles translating the DOM side representation of ngModel
data into the angular model view of the data. $formatters takes the model view and translates it into the DOM appropriate representation. So they are a pair, $parsers goes from DOM to model, $formatters goes back.
Lastly, ngModel
. ngList
processes ngModel
data. So it needs to find an ngModel
directive that has that data ngList should process (which takes us full circle, back to ctrl
)
Upvotes: 5