Day 3

Welcome to Day 3

Make sure you have completed the Code School “Shaping up with AngularJS” tutorials and the free section 2 from Infinite Skills’ AngularJS.  From that you should begin to understand how model and controller are glued using “$scope” and dependency injection.  For conceptual recap visit this explanation DI in a Nushell.

I’ll point you to another usage of scope without the $ sign (first examples in Infinite Skills video) to understand it better.  View this egghead.io video which explains scope is not easily defined in the angularjs documentation itself.   The coding example using the duplicated <kid> tag as a directive first demonstrates all <kid> tags being updated with the same inner HTML text.  Here are two paragraphs in github of the best scope explanation I found.

When the scope property is inserted in the return statement, with a value of empty braces {}, it means that children tags (the subsequent <kid>) do not repeat the input value of the first.  So I’m thinking javascript sets them as unique instances of the subsequent tags.  You will actually see this in the console log of the last scope video. 

This following video demonstrates scope usage with the “&” sign, usually evaluating some expression.    This one is more complicated, but I think of it as binding a function defined in the same module’s controller.  Don’t sweat it for now!  There will be a better explanation in the following days… 

In case you really understood egghead’s video, here’s the third one in the series demonstrating usage of the equal “=” sign to do two-way binding.  Finally, this video explains $scope vs scope the best!  Shall we say $scope is for controllers and scope is for within directives?

To me $scope sounds simple; it is just an object that can hold any data and pass it from module, to controller, to view, etc.  So that’s why some people call it “glue”?   In the first part of the video, we also learn a new property used in custom directives called template instead of templateUrl.  The difference is that “template” expects direct HTML instead of an HTML file.  In future examples we’ll encounter addition restrict values. such as “C” for class, and “M” for comment.

Let’s take the training wheels off and begin coding.  Thanks to Minko Gechev,  here’s an online IDE that’s specific to AngularJS.  It’s a lot like JSfiddle.net but simplified.  Click here to practice your knowledge of scope.

By now we’ve practiced with several examples of outputting and binding data to demonstrate the usage of models, filters, directives. Also the recent examples used the $scope object to pass data from controllers to the view while Code School’s examples used local variables instead.


Let’s move on to a new topic: Routes

Since AngularJS follows the concept of single-page application (SPA) it needs a way to navigate to other pages, thus we have routes.  They kind of work like “includes” because you will see examples with the “templateUrl” property, but routes are more complex and determine what your address bar in the browser will display.  When including routes the very first thing you have to do is include a new angularjs file called angular-route.min.js then you have to include “ngRoute” as a dependency in the module definition as so:

<script src="angularjs/1.2.0/angular-route.min.js"></script>
<script>var app = angular.module('app', ['ngRoute']);</script>

Jump to the 42min mark of Dan’s video up to the 42min mark for another free screencast to learn that routes are created mainly inside the .config() method and the $routeProvider object, containing the “controller” and “templateUrl” properties.  It looks quite simple.

Whatever URL the browser is navigated to, is passed on to $routeProvider which watches for changes using this $location.url()  Then when you have declared the methods .when() and .otherwise() they will pass the controller and specified HTML template to the ng-view directive.

app.config(function ($routePovider) {
$routePovider.when('/view1',
{
controller: "SimpleController",
templateUrl: "view1.html"
})
.otherwise( {  redirectTo: '/' })
});
<div ng-view></div> <!-- data from the router will be injected here -->

What about parameters or a query string in the URL?  (http://mysite.com/somedir/?=’abc’) Well AngularJS has an object for that, it’s called $routeParams.  This needs to be passed as dependency to your controller for usage.  To handle the parameters your .when() method will look like this:

$routeProvider.when('/somedir/:myparam/:myparam2',
{ templateUrl: 'view.html' });

Here’s a completely different example to understand routing better.  It’s a bit more advanced because it’s using a state manager but explained well with code.  State Manager?  What’s that?   First difference is that it uses the ui-view instead of ng-view directive.  A state corresponds to an interface location of your application.  So whereas the router delivers entire sub-pages, the ui-view is for snippets.  It kind of works like a switch statement where each state is an object that contains the name, url, controller, and parent.

Perhaps you didn’t like the previous example on state manager, so check out this one by Joel Hooks, which compares it to ng-switch. That’s enough for today on scope and routes.  Here’s the terminology you should be familiar with now:

Scoping

$scope
scope
restrict: 'A' / 'E' / 'C' / 'M'
template
templateUrl
controller
link

Routing

angular-route.min.js
ngRoute
ng-view
ui-view
$route
$routeProvider
.when()
.otherwise()
redirectTo
.location.url()
myparam
state manager

Congrats on completing Day 3 and visit the day 3 results page to express your concerns or comments.

  • Hi tom, thank you for providing such comprehensive work and take the time to collect links and resources. I’ve worked with angular for a bit now and implemented on a published site. However I am a designer by trade and keep feeling as if I’m not quite grasping the basic concept which is where most tutorials leave you hanging. What happens when best practices need to be applied and not just simple demonstrations of base functionality. All tutorials I have found seem to disregard this and just show the “easy” way out but I feel it leaves too much out and coders like myself risk developing poor code. Things like DRY and separations of concerns are what im eluding to. I’ve worked in php for a while and it is the same conundrum there as there are a myriad of ways I which you can get things done but id not careful can leave applications very vulnerable.

    • runastartup

      You’re welcome Lasse. Feel free to add your tips to the results pages. I agree, I think a lot of tutorials on blogs (not all) are there just for the recognition and publicity. The (top) experienced developers usually have too much work and not enough free time to post practical examples. That’s why I created this, to organize, filter and curate the best content of AngularJS.

    • Thank you! I think its a great idea, just a note, I think the poll asking if you’d like a study buddy is not working correctly I voted “maybe” but it recorded “no”… if I have tips I’d definitely add them but im not sure I am doing things in best practice and therefore hesitant to share my code 🙂 I have been working a bit with angular/wordpress and my sites all run that setup now… if that has interest I can share some of the ways I set it up…

    • runastartup

      I just checked the poll votes and didn’t see your username in the log.

Learn coding in a collaborative team environment.