Search code examples
htmlangularjsdatepickerdirectiveangular-ngmodel

Angular JS - Add ng-model to directive which is called in form


I'm trying to make a date picker which is filling an input text for a form. I've created a directive for that which is called "datepicker".

But now I've a problem, I can't use "ng-model" on directive and I don't know how to solve this problem. The input in the datepicker is need to be filled by the scope "projetData.dateConception" and need to be read by the form.

DatePickerDirective.js:

app.directive("datepicker", function(){
return {
    restrict: 'E',
    replace: true,
    transclude: true,
    scope: {},
    templateUrl: './partials/datepicker.html',
    link: function(scope, element, attrs){

        scope.datepicker = {};
        scope.datepicker.montListShowed = false;
        .
        .
        .

addProjetView.html

<div class = "fiche-line" ng-show="displayField.DateConception">
    <span class="fiche-field-title">Date Conception : </span> 
    <datepicker ng-model="projetData.dateConception" ></datepicker>
</div>
<div class = "fiche-line" ng-show="displayField.DateSolution">
    <span class="fiche-field-title">Date Solution : </span>
    <input type="date" ng-model="projetData.dateSolution" >
</div>

datepicker.html (template of the directive)

<div class="datepicker-relative datepicker-no-touch">
    <input ng-model="datepicker.dateSelected" class="inputDate" ng-focus="datepickerVisible = true" type="text"></input>
    <div class="datepicker-popup" ng-show="datepickerVisible">
    .
    .
    .

The inputs in the form:

Img of the inputs in the form

The datepicker which is filling the input

Img of the datepicker which is filling the input

In conclusion, I want to made the input generated by <datepicker> able to read "projetData.dateConception", modify it. And then the form, on submit, send it to my DB.(already done)


Solution

  • Tanks for your respons, it works now !

    This is how is my code now :


    DatePickerDirective.js :

    app.directive("datepicker", function(){
    return {
        restrict: 'EA',
        replace: true,
        require: 'ngModel',
        transclude: true,
        scope: { ngModel : '='},
        templateUrl: './partials/datepicker.html',
        link: function(scope, element, attrs){
    
            scope.datepicker = {};
    

    addProjetView.html

    <div class = "fiche-line" ng-show="displayField.DateConception">
         <span class="fiche-field-title">Date Conception : </span> 
         <datepicker ng-model="projetData.dateConception" ></datepicker>
    </div>
    

    datepicker.html (template of the directive)

    <div class="datepicker-relative datepicker-no-touch">
            <input ng-model="ngModel" class="datepicker-input-date" type="date"></input>
    </div>