AngularJS控制器实例方法
我有一个angular js控制器,我正在以某种方式编写它,以便其他控制器可以从中继承。我没有将函数定义为angular的控制器函数中的单个函数,而是以以下方式编写它:AngularJS控制器实例方法,angularjs,angularjs-controller,Angularjs,Angularjs Controller,我有一个angular js控制器,我正在以某种方式编写它,以便其他控制器可以从中继承。我没有将函数定义为angular的控制器函数中的单个函数,而是以以下方式编写它: function SomeCtrl($scope) { this.some_field = "1234"; this.scope.externalMethod = angular.bind(this, this.externalMethod); this.scope.anot
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”在该点未解析。有没有办法像本例中那样引用实例方法中的对象?问题已经解决 更新和修复: 好的,我已经调查了这个问题。我应该更新这个问题。它实际上看起来更像这样:
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)
因此,修复方法是首先创建对对象方法的引用。这样我就可以在回调函数中调用它。回调函数中的“this”指的是该函数本身。对不起,虚惊一场…现在已经修复了!感谢@sma的关注。调用“anotherMethod”的是什么?anotherMethod应该从$scope调用。对于仅从$scope本身($scope.anotherMethod)进行的unittest,以及从按钮按下事件直接调用的视图,如果您使用答案更新此帖子,而不是指向问题以在其中找到答案,这将是一件好事。