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:
firstMethod
from secondMethod
? Is the way I did it correct, or is better way?AngularJS application mainly relies on controllers to control the flow of data in the application. A controller is defined using ng-controller directive. A controller is a JavaScript object that contains attributes/properties, and functions.
All the AngularJS application mainly relies on the controllers to control the flow of data in that application. Basically, it controls the data of AngularJS applications and the controller is a Javascript object, created by a standard JavaScript object constructor.
An AngularJS module defines an application. The module is a container for the different parts of an application. The module is a container for the application controllers. Controllers always belong to a module.
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(); }
you call the first method by using $scope.
So
$scope.secondMethod = function() { $scope.firstMethod(); };
Not really sure what you mean in your second question.
For your third quesiton, you can either have the method run automatically "onload" on controller, OR run it via an front-end angular binding.
e.g. Run Automatically
function exampleController($scope) { $scope.sampleArray = new Array(); $scope.firstMethod = function() { //initialize the sampleArray }; $scope.secondMethod = function() { $scope.firstMethod(); }; $scope.secondMethod(); // runs automatically. };
Run on binding
<div ng-controller="ExampleController"> <!-- example controller set up in namespace --> <button class="btn" ng-click="secondMethod()">Run Second Method</button> </div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With