简体   繁体   中英

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 .

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".

The ng-click would be called like this from the html template:

<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.

How can I keep ng-click functions associated with the factory class and its other prototypes?

You could bind the factory method to itself to avoid the issue, but it's a poor workaround.

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 :

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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