繁体   English   中英

控制器中的Angular.js调用指令函数

[英]Angular.js call directive function in controller

我想调用指令中定义的函数,与这个stackoverflow问题恰好相反

我尝试了这个,但是没有用。

app.directive('myDirective', function() {
    return {
        link: function(scope, element, attrs) {
            scope.someDirectiveFn = function(arg) {
                 return "in directive";
            };
        },
    }
});

function MyCtrl($scope) {
    alert($scope.someDirectiveFn());
}

那可能吗? 我怎么能得到它? 这是不好的做法吗?

编辑

我这样子:

.controller('MyCtrl', function($scope) {
    alert($scope.func());
})

.directive('myDirective', function() {
    return {
      controller: function($scope, $element){
        $scope.func = function() {
          return "text";
         };
      }
    }
});

您可以使用事件系统来实现。

首先,使用您的参数在您的范围内发出自定义事件。 其次,使用angular $ on方法监听指令中的作用域。

app.controller('MyCtrl', function($scope) {
  $scope.invokeDirectiveMethod = function() {
    $scope.$emit('invokeMyDirectiveMethod', 'myParameter');
  };
})

.directive('myDirective', function() {
  return {
    link: function(scope, element, attrs) {
      var someDirectiveFn = function(event, arg) {
        alert(arg + " in directive");
      };

      scope.$on('invokeMyDirectiveMethod', someDirectiveFn);
    },
  }
});

这是一个正在工作的朋克

UPDATE

根据您的更新,事件通信不适合您的问题。

如何通过两种方式将对象传递给指令并在该对象中定义someDirectiveFn呢? 这样,您可以传递参数并从中返回值。

app.controller('MyCtrl', function($scope) {
  $scope.shareObject = {};

  $scope.invokeDirectiveMethod = function() {
    if (angular.isFunction($scope.shareObject.someDirectiveFn)) {
      $scope.message = $scope.shareObject.someDirectiveFn('from controller'); 
    }
  };
})

.directive('myDirective', function() {
  return {
    scope: {
      'shareObject': '='
    },
    link: function(scope, element, attrs) {
      scope.shareObject.someDirectiveFn = function(arg) {
        return arg + ' from parameter';
      };
    },
  }
});

更新了插件

您没有发布html代码,所以我假设您的自定义指令在IN MyCtrl 由于执行功能时该方法不起作用。

控制器功能始终在链接功能之前执行。

是一篇有关差异的很酷的文章。

因此,如果希望控制器能够在指令中调用函数,则可以广播事件(如halilb的回答),也可以使指令监听特定的作用域值,如下所示:

app.directive('myDirective', function() {
    return {
        link: function(scope, element, attrs) {
            scope.$watch("message", function() { console.log(message); });
        },
    }
});

function MyCtrl($scope) {
    $scope.message = "Hello Directive";
}

我猜您想拥有一个在指令和控制器之间共享的功能,可以这么说吗?

如果是这样的话,如何创建服务并将服务注入指令和ctrl中。 这样,您只需创建一次即可。

  app.service('sharedFucntionService', function() {
     return {
        someFn : function (arg) {
             alert(arg + " in directive")  
        }
    }
 });

将服务注入指令

 app.directive('myDirective',function( sharedFucntionService){
  return {
        link: function (scope, element, attrs) {
            // do something with sharedFucntionService
        }
    }

});

将服务以及功能MyCtrl($ scope,sharedFucntionService){......}注入控制器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM