简体   繁体   中英

Unable to call javascript prototype function from angularjs

I am trying to call a javascript prototype function from ng-click of hyperlink as follows. But I am unable to fire the getInfo() function on link click. Am i missing any basics or doing wrong?

This is my JS

$(document).ready(function () {
    function Apple() {
        this.type = "fff";
        this.color = "red";

    }
    Apple.prototype.getInfo = function () {
        alert( this.color + ' ' + this.type + ' apple');
    };
    var appl = new Apple();
});

This is my html

  <a href="" ng-click="appl.getInfo()">click</a>

Looking at your above code, I believe the problem is that you're not exposing appl to your via (via the $scope ). You need to do something more like this:

var MyController = function($scope) {
  function Apple() {
    this.type = "fff";
    this.color = "red";

  };
  Apple.prototype.getInfo = function () {
    alert( this.color + ' ' + this.type + ' apple');
  };
  $scope.appl = new Apple();
};

And then:

<div ng-controller="MyController">
   <a href="" ng-click="appl.getInfo()">click</a>
</div>

To elaborate a little more, expressions like the ones passed to Angular's ngClick are evaluated within the context of an Angular $scope (not within the context of their location in the DOM). You can see this by checking out the source of ngClick

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