calling a directive method from controller

血红的双手。 提交于 2020-01-03 03:59:06

问题


I am creating a directive with angular and in that i am using kendo-window control. Now i want to open that kendo window on demand from controller. In simple words i want to call a method of directive from controller on button click.

Here is my code sample

sample.directive('workorderwindow', [initworkorderwindow]);
    function initworkorderwindow() {
        return {
            link: function (scope, elements, attrs) {
            },
            restrict: 'E',
            template: "<div data-kendo-window='window.control' data-k-options='window.config'> HELLOW RORLD </div>",
            scope: {

            },
            controller: function ($scope) {
                $scope.window =
                    {
                        control: null,
                        config: { title: 'HELLO WORLD', visible: false }
                    }
                $scope.open = function () {
                    $scope.window.control.center().open();
                }
            }
        }
    }

HTML

<workorderwindow></workorderwindow>

Now i want to call that directive open method from my controller.

 sample.controller('datacontroller', ['$scope', 'datafac', initcontroller]);
        function initcontroller($scope, datafac) {
            $scope.onsampleclick = function () {
//FROM HERE
            }

回答1:


It's probably a bad practice to directly call a function of your directive from a controller. What you can do is create a Service, call it from your controller and injecting this service in your directive. With a $watch you will be able to trigger your directive function.

The service between Controller and Directive

app.factory('myWindowService', function () {
return {
    windowIsOpen : null,
    openWindow: function () {
        this.windowIsOpen = true;
    },
    closeWindow: function () {
        this.windowIsOpen = false;
    }
};

Your directive :

app.directive('workorderwindow', function () {
return {
    restrict: 'E',
    template: "<div>test</div>",
    controller: function ($scope, myWindowService) {
        $scope.windowService = myWindowService;

        $scope.$watch("windowService.windowIsOpen", function (display) {
            if (display) {
                console.log("in directive");
                //$scope.window.control.center().open();
            }
            // You can close it here too
        });
    }
};
})

And to call it from your controller

app.controller('datacontroller', function ($scope, myWindowService) {
  $scope.open = function () {
      myWindowService.openWindow();
  }
  // $scope.close = ...
});

Here a working Fiddle http://jsfiddle.net/maxdow/ZgpqY/4/



来源:https://stackoverflow.com/questions/23510459/calling-a-directive-method-from-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!