Angular multiple directives error on md-datepicker

379 Views Asked by At

I'm making a dinamic list of dates. The user can adds all datepickers he wants, but I have to validate that there are not matching dates, all of them have to be different, that's the only requisite.

I've made a custom directive validation and it's triggered correctly, but when I try to use its isolate scope, I just get that error (Multiple directives). Other questions/solutions that I've seen here, propose to delete the isolate scope, but I need it to pass to the directive the array of dates and to be able to compare them with the current selected.

Here is a codepen that reproduces the problem. If you remove the noMatchingDates directive's scope, the error just disappears and you can see and add datepickers properly. I mean this scope:

scope: {
  getAllDates: "&allDates"
}

I think that it has to do with this line in docs:

Multiple directives requesting isolated scope.

And it probably also has to do with the md-datepicker which would have more directives using the isolate scope. So, how can I solve this error (and still being able to send the dates list)?

If it can't be solved (keeping the scope) given the nature of the md-datepicker, how can I reach this dynamyc validation? I think it could be done using a controller and the ng-change, but I'm not sure if it would be a proper solution.

1

There are 1 best solutions below

3
On

Indeed there is no reason for your directive to require an isolated scope. Use isolated scope when your directive is like a reusable "visual component". Your directive is about logic validation and shouldn't prevent another such component.

To fix your problem, you can remove the isolated scope and use your directive in the HTML this way:

<div ... no-matching-dates="overtimeList">

Then in your link function, you can retrieve the value of that attribute this way:

var dates = scope.$parse(attr.noMatchingDates);

This will give you the content of what is bound to no-matching-dates, so in this case it will return overtimeList.

I have never used the ctrl.$parsers.unshift syntax, but it seems that you can also use it to retrieve that value. Simply remove the scope.$parse line that I just gave you and write:

ctrl.$parsers.unshift(function(arrayOfDates) { ... })

This should work as well. Note that in the first approach you need to $watch for changes if you want to run the validation every time.