我是 angularjs 的初学者,有一些关于 Controller 的问题。
这是我的示例 Controller :
function exampleController($scope)
{
$scope.sampleArray = new Array();
$scope.firstMethod = function()
{
//initialize the sampleArray
};
$scope.secondMethod = function()
{
this.firstMethod();
};
};
这是我的问题:
- 如何从
secondMethod
调用firstMethod
?我的方法是正确的还是更好的方法? - 如何为 Controller 创建构造函数?我需要调用第二个方法来调用第一个方法来初始化sampleArray?
- 如何从 html 代码调用特定方法?我找到了 ng-initialize,但不知道如何使用它。
最佳答案
您可以按照声明方法的方式调用方法:
$scope.secondMethod = function() {
$scope.firstMethod();
};
您也可以像这样从 HTML 调用:
<span>{{secondMethod()}}</span>
但是 Controller 实际上并没有“构造函数”——它们通常像函数一样使用。但是您可以将初始化放在 Controller 函数中,它将首先执行,就像构造函数一样:
function exampleController($scope) {
$scope.firstMethod = function() {
//initialize the sampleArray
};
$scope.secondMethod = function() {
$scope.firstMethod();
};
$scope.firstMethod();
}
关于javascript - AngularJS Controller 和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14407999/