Angular js Controller Explained

In the below post we will learn about how to create an angular js controller and pass data from angular js controller to angular js view. if you want to learn how to create an angular js module, please refer previous post.

you can create an angular js controller using module’s object controller method as below .

image

Here we have created any angular js module using angular.module method and that object is “myApp”. then we are calling controller method on the object returned from angular js module method. The controller method takes two parameter .

name : This is the name of the controller which you want to create

callBackDefinition : This is the function which you want to initialize.

In the above example I am calling controller method on “myApp” object and passing “HelloWorldController” as name of the controller. The second parameter is callBack function which we want to execute for initializing this controller. The callback function is taking “$scope” object as parameter .

In the simple term , “$scope” is global level object which provide binding between your controller and the view . i.e, you can pass data and behaviour between controller and view using this object .

In the above example I am defining a “message” variable and assigning it to “Hello from My Demo App”. We are display this message to view page as using below configuration .

image

 

Here we are telling angular js that my module is “myDemoApp” using “ng-app” directive and my controller is “HelloWorldController” using “ng-controller”  directive.

image

Here we have applied controller to the div element so all the  public data and behavior( using we assigned to “$scope”) defined under that controller will be accessible under this div. So. here we are trying to access “message” variable using “{{message}}” syntax and browsing this on a web browser should display above output.

 

Thanks for reading . Happy Coding.   

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s