0

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 ?

1 Answer 1

1

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
    };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.