Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
59
rated 0 times [  65] [ 6]  / answers: 1 / hits: 64727  / 12 Years ago, fri, january 18, 2013, 12:00:00

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();
};
};


Here are my questions:




  • How I can call firstMethod from secondMethod? 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.


More From » angularjs

 Answers
2

You call a method the same way you declared it:



$scope.secondMethod = function() {
$scope.firstMethod();
};


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();
}

[#80771] Thursday, January 17, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarettajb

Total Points: 678
Total Questions: 94
Total Answers: 90

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;