本文介绍了AngularJS控制器和方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是angularjs的初学者,有几个关于控制器的问题。
这是我的示例控制器:
I'm a beginner in angularjs with a few questions about controllers.
Here's my example controller:
function exampleController($scope)
{
$scope.sampleArray = new Array();
$scope.firstMethod = function()
{
//initialize the sampleArray
};
$scope.secondMethod = function()
{
this.firstMethod();
};
};
以下是我的问题:
- 如何从
secondMethod
中调用firstMethod
?我的方式是正确的,还是更好的方式? - 如何为控制器创建构造函数?我需要调用调用初始化sampleArray的firstMethod的secondMethod?
- 如何从html代码调用特定方法?我发现ng-initialize但我无法弄清楚如何使用它。
- How I can call
firstMethod
fromsecondMethod
? Is the way I did it correct, or is better way? - How I can create a constructor for the controller? I need to call the secondMethod that call the firstMethod that initialize the sampleArray?
- How I can call a specific method from html code? I found ng-initialize but I can't figure out how to use it.
推荐答案
您以与声明方法相同的方式调用方法:
You call a method the same way you declared it:
$scope.secondMethod = function() {
$scope.firstMethod();
};
您也可以通过HTML调用:
Which you can also call from HTML like so:
<span>{{secondMethod()}}</span>
但是控制器实际上没有构造函数 - 它们通常就像函数一样使用。但是你可以在你的控制器函数中进行初始化,它最初会被执行,就像构造函数一样:
But controllers don't really have "constructors" - they're typically used just like functions. But you can place initialization in your controller function and it will be executed initially, like a constructor:
function exampleController($scope) {
$scope.firstMethod = function() {
//initialize the sampleArray
};
$scope.secondMethod = function() {
$scope.firstMethod();
};
$scope.firstMethod();
}
这篇关于AngularJS控制器和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!