AngularJS Controller实例方法

时间:2015-02-22 11:51:40

标签: angularjs angularjs-controller

我有一个角度js控制器,我正在编写,所以其他控制器可以继承它。我没有在角度控制器功能中将功能定义为单个功能,而是按以下方式编写:

   function SomeCtrl($scope)
   {
       this.some_field = "1234";
       this.scope.externalMethod = angular.bind(this, this.externalMethod);
       this.scope.anotherMethod = angular.bind(this, this.anotherMethod);
       return this;
   }

   SomeCtrl.prototype.externalMethod = function()
   {
       //Do something
       //....(Don't worry about this method, its just to highlight that I can call this method from $scope.externalMethod)
   }

   //These are the methods of interest
   SomeCtrl.prototype.instanceMethodOne = function()
   {
       //Do something....
   }

   SomeCtrl.prototype.anotherMethod = function()
   {
       this.instanceMethodOne(); //---> Problem here!
       //Carry on
       //....
   }

   angular.module('some_module') //Previously defined
   .controller('SomeCtrl', SomeCtrl)

所以我现在遇到的问题是在方法" anotherMethod"中有一个引用(this),它调用类实例方法" instanceMethodOne"。这解析为null作为自引用" this"在那一点上没有得到解决。有没有办法在其实例方法中引用一个对象,就像这种情况一样?

1 个答案:

答案 0 :(得分:0)

问题已经解决。

更新和修正:

好的,所以我调查了这个问题。我应该更新问题。它看起来更像是这样:

   function SomeCtrl($scope)
   {
       this.some_field = "1234";
       this.scope.externalMethod = angular.bind(this, this.externalMethod);
       this.scope.anotherMethod = angular.bind(this, this.anotherMethod);
       return this;
   }

   SomeCtrl.prototype.externalMethod = function()
   {
       //Do something
       //....(Don't worry about this method, its just to highlight that I can call this method from $scope.externalMethod)
   }

   //These are the methods of interest
   SomeCtrl.prototype.instanceMethodOne = function()
   {
       //Do something....
   }

   SomeCtrl.prototype.anotherMethod = function()
   {
       var aCallBack = function()
       {
          //Some stuff...
          this.instanceMethodOne(); //---> Problem here!
       }

       //Carry on
       //....
   }

   angular.module('some_module') //Previously defined
   .controller('SomeCtrl', SomeCtrl)

所以解决方法是首先创建对象方法的引用。这样我就可以在回调函数中调用它。 "这"在回调函数中指的是该函数本身。对不起,误报......现在修好了!感谢@sma对此进行调查。