Displaying content to page using AngularJS

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

To display simple text content to a web page using AngularJS, you use the double curly braces {{ }} to bind AngualrJS expression to elements in the HTML.

But first, we do the normal AngularJS setup.

1. Reference the AngularJS library in the <head>

reference angularjs library

reference AngularJS library

2.  Setup your AngularJS script at the bottom of the page …

angularjs script setup

Angularjs script setup

Details of this pattern explained in our Basic AngularJS Tutorial series.

3. The text content that we want to display is the “Copyright 2015” text.  We want to display that in our page footer, right here where we have added the double curly braces to our HTML …

AngularJS curly braces

AngularJS curly braces

4.  In our AngularJS script tag, we called our app LearnApp and called our controller pageCtrl.  Hook these two references in our HTML…

AngularJS directives

AngularJS directives

These are known as AngularJS directives.  We happen to put them in the body element in this case.

5. Run page in browser to see that our copyright content is displayed in footer of our page…

content displayed in footer

content displayed in footer

6.  As the app gets more complex, it is not ideal to have dynamic variables attached directly to the scope as we did in …

$scope.footerContent

Instead, we should attach only functions or objects to $scope.  We attach an object to our $scope like this…

attaching javascript object to scope

attaching javascript object to scope

This is the Javascript object notation.  And this enables us to add additional content variable (for example maybe headerContent) to our “content” object which we have attached to $scope.  Note that when we do this, we had to change our reference in the double curly braces to …

content.footerContent

That is how we access the data properties within our content object.

7.  While the code currently works.  Let change our code to use the “controller as” syntax as described in our previous tutorial.

replaced $scope with this

replaced $scope with this

Note how our code lost the $scope and “this” was put in its place.

8.  We change the ng-controller to the “controller as” syntax…

controller as syntax

“controller as” syntax

The instance name “ctrl” is arbitrary.  You can all it whatever you want.  “ctrl” is the instance of your pageCtrl controller.

9.  Whatever you call it, you reference it as such here…

reference the controller instance

reference the controller instance

Everything works just like before.

This technique does not work if you want to output raw HTML.  See our next tutorial for a better solution.