Expressions and directives in AngularJS

I hope we had a very perfect concise introduction to AngularJS in our previous post. There we got to know some of the awesome features that AngularJS provides. Also, we came to know that, we can extend the capability of HTML attributes to a great extent with the help of AngularJS directives such as ng-app, ng-bind and ng-model. We also came across the data binding and dependency injection features of AngularJS. We came to know what a scope in AngularJS is. We got a high level idea on the MVC pattern, how it works out in case AngularJS. We also got an idea on the flow of control among different components of an AngularJS application, which we have very nicely illustrated.

Before we start to explore on expressions and directives in AngularJS, I highly recommend you to go through our previous article on Introduction to AngularJS

So an expression in AngularJS is represented as {{name}}. An AngularJS expression binds the data to HTML in the same way as ng-bind directive.

From the below snippet, we can clearly figure out the difference between using a ng-bind directive or an angular expression instead. We can use either of them to serve the same purpose and can be used as each other’s alternative, though ng-bind is said to have a better performance than an angular expression.

Also in the below snippet, we can see some important angular directives being used. With that I hope you can bring out a better picture on the usage of both angular directives and angular expressions.

Below is a separate JS file you need to create:

Make sure you include this JS file into the HTML file in a <script> tag.

Now when we run it, we can see the following getting displayed in the browser:

AngularJS expressions and directives

The usage of the angular directives are as simple to use as you can see it in the above snippet.

Note that, in the HTML markup above, we didn’t specify any ngapp identifier (<div ng-app=””..), which is why we directly started with writing the respective controller function in the JS file. If we instead had specified something like <div ng-app=”xyz”..>, then the JS file would have been like:

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.