Javascript 从同一控制器内的函数调用函数
所以我试图从另一个函数调用一个函数。它们都在同一个Javascript 从同一控制器内的函数调用函数,javascript,angularjs,Javascript,Angularjs,所以我试图从另一个函数调用一个函数。它们都在同一个控制器中定义。但迄今为止,我所尝试的一切都是“功能未定义”。如何正确地做这件事 angular.module('App') .controller('Controller', ['$http', '$scope', function($http, $scope) { this.getSomething1 = function() {}; this.getSomething2 = function() { if
控制器中定义。但迄今为止,我所尝试的一切都是“功能未定义”
。如何正确地做这件事
angular.module('App')
.controller('Controller', ['$http', '$scope', function($http, $scope) {
this.getSomething1 = function() {};
this.getSomething2 = function() {
if (1 == 1) {
getSomething1();
}
};
}]);
ReferenceError:未定义getSomething1
您需要调用this.getSomething1(),但有一个问题 这里的问题是函数内部的
此
并不总是与函数外部的此
相同。为了安全起见,将控制器this
保存在变量中,并使用该变量调用函数:
angular.module('App')
.controller('Controller', ['$http', '$scope', function ($http, $scope) {
var vm = this;
vm.getSomething1 = function () {
};
vm.getSomething2 = function () {
if(1 == 1){
vm.getSomething1();
}
};
}
]);
另一个可以使代码更清晰的选项是始终使用命名函数。您仍然可以在控制器上公开它们中的任何一个,但也可以直接调用它们
angular.module('App')
.controller('Controller', ['$http', '$scope', function ($http, $scope) {
angular.extend(this, { getSomething1: getSomething1, getSomething2: getSomething2 });
return;
function getSomething1() {
};
function getSomething2() {
if(1 == 1){
getSomething1();
}
};
}
]);
这还有一个好处,即在控制器顶部分离初始化代码,而不是将其分散在函数声明中
如果可以使用ES2016语法,则extend
调用看起来更干净:
angular.extend(this, { getSomething1, getSomething2 });
尝试在控制器中使用范围变量而不是此变量
angular.module('App')
.controller('Controller', ['$http', '$scope', function ($http, $scope) {
var scope = $scope
scope.getSomething1 = function () {
};
scope.getSomething2 = function () {
if(1 == 1){
scope.getSomething1();
}
};
}
]);
您还可以使用函数语法声明控制器,如下所示:
(function() {
'use strict';
angular
.module('App')
.controller('Controller', Controller);
/** @ngInject */
function Controller($http, $scope) {
var scope = $scope
scope.getSomething1 = function () {
};
scope.getSomething2 = function () {
if(1 == 1){
scope.getSomething1();
}
};
}
})();
使用
$scope
而不是此
angular.module('App')
.controller('Controller', ['$http', '$scope', function($http, $scope) {
$scope.getSomething1 = function() {};//<=== use of $scope
this.getSomething2 = function() {
if (1 == 1) {
$scope.getSomething1(); //<=== use of $scope
}
};
}]);
angular.module('App')
.controller('controller',['$http','$scope',函数($http,$scope){
$scope.getSomething1=function(){};//您可以尝试使用$scope来代替这个
angular.module('App')
.controller('Controller', ['$http', '$scope', function($http, $scope) {
$scope.getSomething1 = function() {};
$scope.getSomething2 = function() {
if (1 == 1) {
$scope.getSomething1();
}
};
}]);
我假设您尝试了this.getSomething1();
?我通常在$scope
上定义我的函数,但是..$scope.getSomething1=function(){…}
并通过$scope.getSomething1()调用它;
@Arg0n,是的。它给了我类型错误:this.getSomething1不是一个函数
你应该把其他函数放在一个服务中,用太多的代码混乱控制器方法是不好的设计,相反,我会把它绑定到$scope,尽管使用这个
和“控制器作为”要好得多语法的形式。这会起作用,但命名函数方法听起来更好,不仅因为它可以工作,而且更干净。在作用域中添加方法将使它们暴露于视图中(至少对于私有的方法)。