Nayeem Mansoori
Nayeem Mansoori

Reputation: 831

How to call controller function from directives

I'm using Angularjs and I want to call controller function from directives but it is not working please help.

Below my code

app.directive('datetimez', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            element.datetimepicker({
                dateFormat: 'dd-mm-yyyy'
            }).on('changeDate', function (e) {
                changedate();
                //ngModelCtrl.$setViewValue(e.date);
                //scope.$apply();
            });
        }
    };
});

Controller :

app.controller('GetIncidentcnt', function ($scope) {

    $scope.changedate = function () {
        alert('Hi#####fromdate');
    }
});

HTML:

<div id="date" class="input-append" datetimez ng-model="var1">
    <input data-format="dd-MM-yyyy" type="text" id="input1" data-date-start-date="+0d" name="input1"></input>
    <span class="add-on">
        <i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
    </span>
</div>

I want to call changedate() from directive function

Upvotes: 0

Views: 290

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

As you can have a case where you need to use it multiple times on your page, In that case calling controller method from directive will get messed up, when you wanted to call different method on each datepicker.

So I'd suggest you to use isolated scope there to make a reusable component. For that you need to add scope: { onChange: '&' },, that will make available to directive using & (which indicates expression to executed)by adding on-change attribute on your directive element that will provide the controller method contract.

Markup

<div id="date" class="input-append" datetimez ng-model="var1" on-change="changedate()">

Directive

   app.directive('datetimez', function () {
        return {
            restrict: 'A',
            scope: {
               onChange: '&'
            },
            require: 'ngModel',
            link: function (scope, element, attrs, ngModelCtrl) {
                element.datetimepicker({
                    dateFormat: 'dd-mm-yyyy'
                }).on('changeDate', function (e) {
                    //to run digest cycle to..
                    scope.$apply(function(){
                       scope.onChange();
                    })

                });
            }
        };
    });

Upvotes: 3

sdgluck
sdgluck

Reputation: 27237

Providing the directive is declared within the controller's scope (in a template) you simply need to reference the method on the directive's inherited scope object, given as an argument to the link method:

link: function (scope, element, attrs, ngModelCtrl) {
    element.datetimepicker({
        dateFormat: 'dd-mm-yyyy'
    }).on('changeDate', function (e) {
        scope.changedate();
//      ^^^^^
    });
}

Upvotes: 1

Related Questions