Angular Controllers
Using “as aliasName” specifier when defining the controller in ng-controller directive. The methods and properties can be bound on to the controller using “this” keyword. There are benefits of binding properties directly to the controller and thus, it is the recommended way (best practice) to declare the controller using “as alias” method. Following are some of the benefits:
Following is how view code looks like. Note the “as ctrl” and then, “ctrl.name”
<div ng-controller="HelloCtrl as ctrl">
<input type="text" name="name" ng-model="ctrl.name"/>
</div>
Following is how the controller looks like:
angular.module( "helloApp", [] )
.controller( "HelloCtrl", function() {
this.name = '';
}]);
This is most common and popular way of working with the controller. For rookies to quickly get on board, this may be the recommended way.
In this strategy, the properties and methods get bound as scope properties and methods and can be later accessed on scope object within the controller object. This strategy requires $scope object to be injected.
Following is how view code looks like. Note the absence of “as” in the ng-controller directive and “ctrl.” alias in ng-model directive.
<div ng-controller="HelloCtrl">
<input type="text" name="name" ng-model="name"/>
</div>
Following is how the controller looks like. Notice that $scope is injected and the model is bound to $scope object.
angular.module( "helloApp", [] )
.controller( "HelloCtrl", [ '$scope', function( $scope ) {
$scope.name = '';
}]);
…
[adsenseyu1]
Last updated: 25th Jan, 2025 Have you ever wondered how to seamlessly integrate the vast…
Hey there! As I venture into building agentic MEAN apps with LangChain.js, I wanted to…
Software-as-a-Service (SaaS) providers have long relied on traditional chatbot solutions like AWS Lex and Google…
Retrieval-Augmented Generation (RAG) is an innovative generative AI method that combines retrieval-based search with large…
The combination of Retrieval-Augmented Generation (RAG) and powerful language models enables the development of sophisticated…
Have you ever wondered how to use OpenAI APIs to create custom chatbots? With advancements…
View Comments
another way is registering a controller using a $controllerProvider. Then use the $controller service to create it. You can pass the $scope as parameters to $controller service.