在 AngularJS 中,如何使指令成为对象,以便可以向它“传递消息”(在其上调用方法)

In AngularJS, how do you make a directive an object, so that you can "pass messages" to it (invoke method on it)?

本文关键字:传递消息 消息 方法 调用 可以向 何使 AngularJS 指令 对象      更新时间:2023-09-26

我对CanJS非常熟悉,有点像你可以在HTML元素上实例化自定义Web小部件的想法,现在我们有一个对象,我们可以向它发送消息(调用它的方法):

lightbox.popUp();

reviewStars.setStars(3.5);

如何在AngularJS中做到这一点? 在你创建一个指令并将其设置在HTML元素上或将该指令用作HTML元素之后,你如何做类似上面的事情,就像在OOP中一样,或者Smalltalk会如何做到这一点 - 向特定对象发送消息?

我可以想到一种方法,例如:

<review-stars api="ctrl.reviewStarAPI"></review-stars>

然后对于 reviewStar 指令,执行以下操作:

scope: { api: "=" }
link: function(scope, elem, attrs) {
    // first define some functions
    scope.setStars = function(n) { ... };
    // and then set it to the api object:
    scope.api.setStars = scope.setStars();
}

然后在控制器中,执行

vm.reviewStarAPI.setStars(3.5);

但这有点混乱,而且有些临时。 而且它总是需要一个控制器...虽然,我想我们可以使用 1 个控制器作为主程序并实例化一堆对象,然后以这种方式调用它们的方法。

除了上述方法之外,还有什么方法可以实现此目的?

实现此目的的模块化方法是创建一个名为 reviewStars 的指令。该指令应具有指示星级的参数。

例如: <review-stars rating="3.5">

您可以使用如下所示的内容进行创建:

angular.module('myAngularModule', [])
.directive('reviewStars', function() {
  return {
    restrict: 'E',
    scope: {},
    bindToController: {
      rating: '@'
    },
    link: function(scope, elem, attrs) {
      // instantiate the lightbox code here
    },
    controller: function () {
      var vm = this;
      // controller code goes here (e.g. the onClick event handler)
    },
    controllerAs: 'ctrl',
    templateUrl: 'review-stars.html' // the HTML code goes in this file
  };
});

查看Rangle的ng-course(https://github.com/rangle/ngcourse)或Angular文档(docs.angularjs.org),了解有关指令的更多信息。