【问题标题】:Angularjs directive, maintaining internal state for each of the directive instanceAngularjs 指令,维护每个指令实例的内部状态
【发布时间】:2016-04-03 03:23:03
【问题描述】:

我有一个依赖于服务的指令,我在服务中维护一些指令状态。 因此,每当在两个地方使用相同的指令时,它都需要实例化新服务。 例如,

<body>
 First directive instance: <custom-directive> 1 </custom-directive>
 Second directive instance: <custom-directive> 2 </custom-directive> 
</body>

在这种情况下,两个控制器都填充了相同的服务对象,但我需要不同的服务对象在内部维护它们的状态。

谁能帮忙。

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    您仍然可以使用服务/工厂,但在您的服务中公开一个 getInstance 方法,该方法返回一个新实例,允许您注入并随后为每个指令创建一个新实例。

    angular.module('app', []).factory('sharedService', sharedService);
    
    function sharedService() {
        return {
            getInstance: function () {
                return new instance();
            }
        }
    
        function instance() {
            // functionality
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-25
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-13
      • 1970-01-01
      • 2014-05-12
      相关资源
      最近更新 更多