如何在其他指令中调用一个指令的函数?

时间:2017-09-13 13:36:35

标签: javascript angularjs function angular-directive angular-controller

指令1

angular.module('mwFormViewer').directive('mwFormViewer', ["$rootScope", function ($rootScope) {

    return {
        replace: true,
        restrict: 'AE',
        scope: {
            formData: '=',
        },
        templateUrl: 'public/angular-survey/viewer/templates/bootstrap/mw-form-viewer.html',
        controllerAs: 'ctrl',
        bindToController: true,
        controller: ["$timeout", "$interpolate", function($timeout, $interpolate){
            var ctrl = this;
            ctrl.beginResponse=function() {
               if(ctrl.formData.pages.length>0){
                  $rootScope.$broadcast('time-start');
               }
            }
        };
});

指令2

angular.module('mwFormViewer').directive('timer', function($timeout, $compile) {
  return {
    restrict: 'E',
    transclude: true,
    controllerAs: 'ctrl',
    bindToController: true,
    controller: function(){
        var ctrl = this;
    },
    scope: {
        interval: '='
    },
    link: function(scope, elem, attrs, $ctrl) {
        function start() {
           console.log('start');
        }

       //Watches
       scope.$on('time-start', function() {
           console.log('started')
           start();
       });
    }
});

我正在尝试从directive1调用command2的start()。我使用广播,但它不起作用。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

ctrl.beginResponse=function() {
   if(ctrl.formData.pages.length>0){
       $rootScope.$broadcast('time-start');
   }
}

if(ctrl.formData.pages.length>0)条件为假。这就是为什么$rootScope.$broadcast('time-start');没有被广播的原因。