[英]Call a function from function inside the same controller
所以我想调用一个function
从another function
。 并且它们都在同一个Controller
定义。 但是到目前为止我已经尝试过的所有内容都是"funtion is not defined"
的最佳状态。 如何正确地做这件事?
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
里面的函数并不总是一样的this
外面。 所以为了安全起见,保存控制器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
而不是this
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
}
};
}]);
这样,您可以在控制器中使用getSomething1方法(在js中)和您使用控制器的网页本身(在html中)
您可以尝试使用$ scope而不是此。
angular.module('App')
.controller('Controller', ['$http', '$scope', function($http, $scope) {
$scope.getSomething1 = function() {};
$scope.getSomething2 = function() {
if (1 == 1) {
$scope.getSomething1();
}
};
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.