Slimshadddyyy
Slimshadddyyy

Reputation: 4073

AngularJS - Call Controller function from Directive

HTML

angular.element(document.querySelector('#dateControls')).append($compile("<search-date></search-date>")($scope));

Directive

myApp.directive('searchDate', function ($compile, $rootScope,$timeout) {
    var linker = function (scope, element, attrs) {

            var template =  '<button class="btn btn-default" ng-click="dateSearch() id="playbackSearch" search-date">Search</button>';

            element.html(template);
            $compile(element.contents())(scope);

    };
    return {
        restrict: "EA",
        replace: true,
        link: linker
    };
});

Controller

$scope.dateSearch = function(){

    scope.userId = 1;
    myModuleService.getData(userId) //call service
    then(function (data) {
    console.log(data);

    }).catch(function (error) {
        throw error;
    });
};

How do I call function dateSearch() defined in my controller ?

Upvotes: 0

Views: 69

Answers (1)

saiyan
saiyan

Reputation: 572

You can add a controller in directive itself.Since your myModuleService is external service

like

controller:function($scope,myModuleService)
{

$scope.dateSearch = function(){

    scope.userId = 1;
    myModuleService.getData(userId) //call service
    then(function (data) {
    console.log(data);

    }).catch(function (error) {
        throw error;
    });
};

}

or in your style

var controll:function($scope,myModuleService)
    {

    $scope.dateSearch = function(){

        scope.userId = 1;
        myModuleService.getData(userId) //call service
        then(function (data) {
        console.log(data);

        }).catch(function (error) {
            throw error;
        });
    };

    }
 return {
        restrict: "EA",
        replace: true,
        link: linker,
        controller:controll
    };

Upvotes: 1

Related Questions