简体   繁体   English

在ng-click上分解Angular工厂原型

[英]Angular factory prototype dissociation on ng-click

I have a factory that has a series of prototypes that need to be able to call each other. 我有一家工厂,工厂里有一系列需要相互调用的原型。 The problem is the reference to "this" is being applied to the html template rather than the original factory class when using ng-click . 问题是使用ng-click时,将对this的引用应用于html模板,而不是原始工厂类。

Here is an example: 这是一个例子:

angular.factory('myFactory', function(){
    function FactoryA(){}
    FactoryA.prototype.hello = function(){ console.log('Hello') };
    FactoryA.prototype.useHello = function(){ this.hello() };

    return FactoryA;
}

The controller will set the factory to $scope variable "myFactory". 控制器会将工厂设置为$ scope变量“ myFactory”。

The ng-click would be called like this from the html template: 从html模板中将这样调用ng-click

<button type="button" ng-click="myFactory.useHello()">Hello</button>

The problem is that "this" in the context of myFactory.useHello is replaced by the html template reference and loses its link to FactoryA and its other prototypes. 问题是myFactory.useHello上下文中的“ this”被html模板引用替换,并且失去了与FactoryA及其其他原型的链接。

How can I keep ng-click functions associated with the factory class and its other prototypes? 如何保持ng-click函数与factory类及其其他原型相关联?

You could bind the factory method to itself to avoid the issue, but it's a poor workaround. 您可以将factory方法绑定到自身以避免发生此问题,但这是一个较差的解决方法。

As @ste2425 said, you should declare an handler in your controller which will execute the call to the service method and use this handler in your template : 正如@ ste2425所说,您应该在控制器中声明一个处理程序,该处理程序将执行对service方法的调用,并在模板中使用此处理程序:

<button type="button" ng-click="useHello()">Hello</button>

And in your controller : 在您的控制器中:

$scope.useHello = function() {
    myFactory.useHello();    
}

Also, using prototypal declaration for factories/service, which are singleton by design, is kinda useless. 而且,对工厂/服务使用原型声明,这些声明在设计上是单例的,这是没有用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM