从角度工厂或指令导出方法以供以后使用

Exporting methods from an angular factory or directive to use later

本文关键字:方法 工厂 指令      更新时间:2023-09-26

我使用Angular开发了一个Web应用程序.js(这是我的第一个)。该应用程序具有一系列交互式图形(座位图);所以我创建了一个模块来处理 Raphael 的东西,包括一个指令,如下所示:

angular.module('raphael', [])
.factory('fillData', function() {
  return function(paper, data) {
    var canvas = $(paper.canvas);
    // Do fill the data and more ...
    canvas.on('click', '[id]', function(e) {
      this.classList.toggle('selected');
    });
  };
})
.directive('raphael', ['fillData',
  function(fillData) {
    return {
      scope: {
        raphael : '&',
        seatData: '&'
      },
      link: function(scope, element, attrs) {
        var paper = null;
        var updateSeatData = function() {
          if(scope.seatData()) fillData(paper, scope.seatData());
        };
        scope.$watch(scope.raphael, function() {
          element.empty();
          paper = new Raphael(element[0], '100%', '100%');
          paper.add(scope.raphael());
          updateSeatData();
        });
        scope.$watch(scope.seatData, function() {
          updateSeatData();
        });
      }
    };
  }
]);

一切正常,直到我们需要在另一个级别中与向量进行交互。假设,获取所选席位的计数,或取消选择所有席位(由文档中的某个随机元素触发)。我似乎无法找到实现它的合理方法。

你有什么建议?有没有其他方法可以在 angular 中使用第二个库?

据我了解,您希望具有某些内部状态的指令,但您希望从外部访问其状态(其他指令,服务等)。如果是这样,那么似乎您可以将服务用作状态持有人。在这种情况下,您的指令不会保存状态,但它将访问它。

你说的合理实现方式是什么意思?它看起来不错,尽管我更愿意绑定到属性 seatData 而不是传递函数,例如

scope: {
  seatData: '='
}

然后观看

scope.$watch('seatData', function() {
  fillData(paper, scope.seatData);
});

这是你的问题还是我没有理解?

好的,这是我提出的解决方案;我访问了父范围并将基本方法放在那里。

将此行添加到fillData工厂:

return {
  deselectAll: function() { ... }
};

并将updateSeatData方法更改为:

var updateSeatData = function() {
  if(scope.seatData) {
    var result = fillData(paper, scope.seatData[scope.level]);
    angular.extend(scope.$parent, result);
  }
};

附言仍然愿意听到更多...