javascript - Angular.js 在 Controller 中调用指令函数

标签 javascript angularjs angularjs-directive

我想调用指令中定义的函数,与this stackoverflow question相反

我尝试过这个,但不起作用。

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

这是一个工作 plunker .

更新

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

如何使用双向绑定(bind)将对象传递给指令并在该对象中定义 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';
      };
    },
  }
});

已更新plunker .

关于javascript - Angular.js 在 Controller 中调用指令函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26805642/

相关文章:

javascript - 使用 css 选择器和 javascript 断言随按钮单击而更改的文本

javascript - 使用 Angular Material 展开折叠列表项

javascript - ngModel.setViewValue 不更新 html 控件

javascript - Angular 指令 - Attr 中的嵌套对象

javascript - 将工厂注入(inject)服务失败

angularjs - 另一个指令的 templateUrl 内的指令和传递属性

javascript - 下载所有外部链接,例如(pdf/图像)必须自动下载

javascript - 复制一个对象并更改此复制变量不会改变原始对象吗?

javascript - 了解 eval() 的用法来评估 bool 值

javascript - 使用 Jasmine 在 AngularJS 中测试去抖函数永远不会调用该函数