【问题标题】:How to call custom directive programmatically in angularjs如何在angularjs中以编程方式调用自定义指令
【发布时间】:2015-12-21 16:09:13
【问题描述】:

有没有办法从控制器内部的函数调用自定义指令函数。

var m=angular.module('myApp',[]).controller('test',function($scope){
//here i want to call input directive

});

m.directive('input', function() {});

【问题讨论】:

  • 这不是直接定义对象的主要意图。请详细说明您的情况。

标签: javascript angularjs angularjs-directive


【解决方案1】:

调用指令函数需要使用事件调度:

var m=angular.module('myApp',[]).controller('test',function($rootScope){
  $rootScope.$emit('event-response', result);
  ...
});

m.directive('input', function($rootScope) {
  ...
  $rootScope.$on('event-response', function (args) {
    //function call...
  });
 .....
});

更新

我们可以使用共享作用域将功能从指令添加到父控制器。 它不太可能从父控制器范围继承,因为这种方式会产生非常强的耦合,并且您需要记住在重用此指令时是从父控制器继承的。

var m=angular.module('myApp',[]).controller('test',function($scope){
  $scope.myFunc() // available from `input` directive
  ...
});

m.directive('input', function() {
  return {
    scope: false, // scope is shared with parent controller
    controller: function($scope) {
      $scope.myFunc = function() {
        ...
      };
    }
  };
});

【讨论】:

    【解决方案2】:

    您可以将控制器的对象传递给指令,并在指令上为该对象分配指令的功能。

    我创建了 plunker 让你看看:http://plnkr.co/edit/JEb5dzefEgZM5N79kbT5?p=preview

    HTML sn-p:

    <body ng-controller="test">
       <input-test control="customControl"></input-test>
       <button ng-click="customControl.directiveFunction()">PRESS ME</button>
    </body>
    

    App.js

    var m=angular.module('myApp',[]).controller('test',function($scope){
      $scope.customControl = {
      };
    });
    
    m.directive('inputTest', function($window) {
      return {
        restrict: 'E',
        template: '<div>TEST</div>',
        scope: {
          control: '='
        },
        link:function (scope, element, attrs) {
          //here is where we assign to our "control" (passed on directive's declaration) the directive function
          scope.control.directiveFunction = function() {
            $window.alert("CALLED"); 
          }
        }
      };
    });
    

    【讨论】:

      【解决方案3】:

      使用指令而不是服务背后是否有特定原因,因为服务在这里会派上用场。

      使用服务很容易,如果这对您有意义,请看下面的示例。

      var app = angular.module('app', []);
      
      app.service('testService', function(){
          this.testFunc = function () {
              return "Hello";
          };
      });
      
      app.controller('appController', function($scope, testService) {
          $scope.valueFromService = testService.testFunc();
      
      });
      

      要查看使用指令、工厂和服务之间的区别,请查看此链接:

      Difference between service, directive and module

      【讨论】:

        猜你喜欢
        • 2015-09-16
        • 1970-01-01
        • 2013-05-15
        • 2013-05-28
        • 2023-03-27
        • 2013-09-23
        • 2020-10-28
        • 2016-09-08
        • 1970-01-01
        相关资源
        最近更新 更多