AngularJS - 来自Directive的呼叫控制器功能

时间:2016-08-13 06:58:31

标签: javascript angularjs angularjs-directive

HTML

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

指令

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
    };
});

控制器

$scope.dateSearch = function(){

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

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

如何调用控制器中定义的函数dateSearch()

1 个答案:

答案 0 :(得分:1)

您可以在指令中添加控制器。因为您的myModuleService是外部服务

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;
    });
};

}

或以你的风格

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
    };
相关问题