Blogger news

Blogger templates

Thursday, July 17, 2014

Controllers in AngularJS

If you are new to AngularJS I would prefer to go through my introduction blog on AngularJS before read this article

In Angular, a Controller is a JavaScript constructor function. Before Jump to details of controllers you should know about $scope object so I will give a brief introduction about $scope

Scope is nothing but an object that Glues the View with Controller. They hold the Model data that we need to pass to view. Scope uses Angular’s two-way data binding to bind model data to view.

Imaging $scope as an object that links Controller to the View. It is controllers responsibility to initialize the data that the view needs to display. This is done by making changes to $scope. See the example below
    $scope.hellomessage = "Hello AngularJS";
Here we created a controller called 'FirstController' and injected $scope object then we set a property, hellomessage. Now we have to tell our view about controller. see code below
<!DOCTYPE html>
<html ng-app="FirstModule">
<head lang="en">
    <meta charset="UTF-8">
    <script src="../Scripts/AngularScripts/angular.min.js"></script>
    <script src="../Modules/HelloWorldModule.js"></script>
    <script src="../Controllers/HelloWorldController.js"></script>
<body ng-controller="FirstController">
Now our view knows about the controller and it can access hellomessage  property. 
This attribute defines a Controller to be bound with the view. In this case we defined a controller called FirstController in body using ng-controller attribute. Thus whatever we put inside html, the FirstController will have its influence on it. Body is parent level but we can give controller to any child level
FirstController is nothing but a JavaScript function. There is an object $scope which we pass as an argument. This object is used to bind the controller with view. When AngularJS initialize this controller, it automatically creates and injects the $scope object to this function using dependency injection.
Calling functions on the controller
So we’ve seen how to initialize data on the scope from the controller, but what if we want to call a method on the controller from our page — like when a button is clicked. Say we have a button like below (I am assuming you already inform view about your controller)
     <button ng-click="Clicked()">Click Me</button>
 Notice that this is just a simple method call. It will look for this method on the scope. So let’s add a method to the scope from our controller in order to handle this. Add this inside the controller:
    $scope.Clicked= function() {
 clicking the button will now alert the message "Clicked!!!!".
Conclusion:- anything  which is attached to $scope object  in controller can be accessible from view 
If you are not aware "FirstModule" in my example please go throught my blog on Introduction to AngularJS

No comments:

Post a Comment