Beginning AngularJS

(WallPaper) #1
Chapter 8 ■ Organizing Views

Of course, there’s probably not much point in using the function-based alternative in this example. It’s easier
and much clearer to use the string-based approach. The real strength of the function-based approach is that it
can be dynamic.
The example in Listing 8-18 does it much more justice. Here, we assume that we have ten portfolio pages, each
one featuring a different piece of work. Each piece of work has its own view template, named portfolio1.html,
portfolio2.html, portfolio3.html, all the way through to portfolio10.html.


Listing 8-18. A Dynamic templateUrl Value


when('/portfolio', {
templateUrl: function () {
// create a number between 1 and 10
var num = Math.floor((Math.random() * 10) + 1);
// use this number to produce a path
// to one of the ten view templates
return 'pages/portfolio' + num + '.html';
},
controller: 'contactController'
});


The function assigned to templateUrl is now a bit more interesting. This function creates a random number
between 1 and 10, and it appends this number to the end of the file name. Each time the function runs, a different file
name is created. Consequently, a potentially different portfolio view template is displayed each time.


HTML5 Mode

I made the point earlier in the chapter that, by default, links are declared using a # character. The # character is only
there because we don’t want the browser to fire off an actual HTTP request to the server. For example, if we removed
it, a URL like the one following would create a request to the server.


http://mydomain/index.html/about


However, if we keep the # character as we do in the following URL, the browser will not fire off an HTTP request
to the server, because the # character is telling it that we are seeking content on some part of the same page—the page
that is currently loaded.


http://mydomain/index.html#/about


In reality, this whole approach is really just a workaround for non-HTML5 browsers. It works well, and it is
perhaps the best approach to use if you are unsure who your target audience might be. However, a cleaner option
exists. You can enable HTML mode. In this mode, the # character is not needed. A couple of reasons to do this might
be that you want prettier URLs and much more SEO-friendly URLs.
Enabling HTML5 mode is not terribly difficult, but it does require some web server configuration and a relatively
good understanding of how browsers and web servers handle links. I chose to remain in default mode, so as not
to muddy the waters in this introductory book, but you should be aware of this option, and I encourage you to
investigate further.


■ Tip Official coverage of htML5 mode can be found at https://docs.angularjs.org/guide/$location.

Free download pdf