Skip to content

Instantly share code, notes, and snippets.

@RobAWilkinson
Last active August 29, 2015 14:21
Show Gist options
  • Save RobAWilkinson/56e62f70f91e35bc83dd to your computer and use it in GitHub Desktop.
Save RobAWilkinson/56e62f70f91e35bc83dd to your computer and use it in GitHub Desktop.

#Intro to Angular

###learning objectives

  • create a page with a two data binding between controller and view

##Why angular Angular is a way to allow for fast highly responsive full featured single page apps

Take a look at this code right here and see what people were building pre-angular

<body>
Name: <input id="name" type="text">
Age: <input id="age" type="text">


<script>
  Person = function(){
    this.name = document.getElementById('name').value;
    this.age = document.getElementById('age').value;
  }
  function logPerson() {
    var person = new Person();
    console.log(person);
  }

  window.setInterval(logPerson,100);
</script>

All we're really doing is using javascript to watch some input fields, create an object with it and log it. We set an interval to do this but we could have also done it on any event, on change every millisecond and so on and so forth.

Imagine if we have to watch a ton of different models and create tons of objects, send that data to a server, change our html in cool and fantastic ways and so on. This could get really bulky and hard to maintain.

Just understand, angular isn't doing anything magical, its just abstracting away some of the complexity for us.

##Angular basics

  • Programming a web app with AngularJS requires a different mindset.
  • To use AngularJS effectively, it helps to think of your application being driven by data - you change data, the app responds.
  • We naturally think more procedurally when coding, we attach an event handler and write code to respond...
  • Let's look at an example of the different approaches. Say we want an edit form to show when a button is clicked:
  • Procedurally, we would attach an event handler to the button. The handler code would select the element and set it's display property to something besides "none".
  • Using AngularJS, we declare a click handler on the Button element. The handler could set a variable named editMode equal to true, and the view would respond automatically.
  • Remember, drive your application using data - your data model is the single source of truth!

Angular apps can get complicated, to try to minimize this we have to keep a careful eye on the global scope and watch what happens!

  • can anyone remind me how things are scoped using javascript? We are enviromentally friendly here, don't pollute the global scope

Angular is an MVC framework!

The controller pulls data from the model and displays it in the view!

###how angular works angular is built up out of directives that live in our html, things like ng-app, ng-controller and so on. When our page gets loaded the html is created first then angular goes back and looks for directives and updates the html accordingly.

###Angular Controllers

Angular controllers are basically constructor functions that are new'd up when our app is loaded in the view.

Can anyone remind me of what a constructor function is?

We bind things to the controller in angular, then we can access them in the view.

###Putting this into practice

Make a new folder in your workspace with a blank index.html and a js/ folder in there, your tree should look like

.
├── index.html
└── js
    └── app.js

Open up the index.html and put the standard html5 boilerplate in there then lets source angular in from the CDN
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> and our app.js as well <script src="js/app.js"></script>

###Creating our app With angular, we declare all the pieces of our code within a single module, a module is just a way of grouping chunks of code together. in our app.js we create an initial angular module

angular
  .module('myApp',[]);

Notice the empty array, if we need to include any external dependencies, whether from other modules we have written or a module someone else wrote we insert it here We only have to define these external dependencies once, everywhere else we just refer back to the same module that we've already created.

Now that we've instantiated an app in our javascript we need to refer to it in out html we use the ng-app directive in our body tag

<body ng-app="myApp">
{{ 10 *3 }}

</body>

This tells angular that anything in the body is going to be part of this app.

We can do math in here, execute javascript code and dsiplay stuff, we just have to make sure to wrap it in double curly braces{{ stuff }}

(Or use ng-bind)

###Defining a controller Lets define a controller so that we can actually do something In Angular's flavour of MVC controllers are intended primarily to

  • Respond to user actions.
  • Provide data to the view (occasionally referred to the view-model).

To write good clean code we separate our different controllers into different files

make a new file in your js folder js/homeController.js and src it in your html

In that file we create a brand new controller on our same angular app

// When only the name of the module is passed in,
// the 'module' method returns the specified module.
angular.module('myApp')
    .controller('HomeController', HomeController);

// This is the function definition for our controller.
// Note that we capitalize it as it is used as a constructor function!
function HomeController() {

}

For those of you that noticed that we are polluting the global scope with our HomeController function - good eye! Feel free to wrap all the code in an IIFE (Immediately Invoked Function Expression)!

Now, there are two acceptable methods for defining controllers. They are commonly referred to as the:

  • $scope method
  • controller as method

The controller as method should look familiar to you all, its a classic programming paradigm, we're just using the controller as a constructor function and accessing its various methods and properties in the view

##Hook this up in your view

in our body we use another directive, ng-controller to tell angular this div belongs to a certain controller.

We alias it so that we can access its various properties and methods in your html

<div ng-controller="HomeController as homeCtrl">


</div>

Inside of this div we can access various methods and properties that we define on our controller.

I want to introduce the concept of a capture variable, it basically gives us a variable that is bond to this at a certain level, and we bind different things to that throughout our code. Remember javascript is functionally scoped when we declare a variable within a function. this won't always refer to what you thinkk. To take care of this people place a line like this right at the top of their controller function.

var ctrl = this;

how can we define a property testString in our controller and set it equal to "testing"?

Once we do that we can access it in our html using the double curly braces

{{ ctrl.testString }}

Did it display for you?

Weve set it up so that we can display data from our controller in our view, do you think that we can make what the user types in in our html available to our controller?

If you said yes, you're right!

the angular directive for this is ng-model remember the vanilla javascript page that we were trying to recreate? What object was created? What properties did it have?

lets create that object in our angular controller

ctrl.person = {
  name: "Rob"
};

We want this data to be available in our controller we define it as a property of that controller in our view

<input ng-model="homeCtrl.person.name">

Whoa look at that! its connected up to our controller data here! Try adding a field with your age in it as well

the interesting thing is that we can change these values now, after all, they are input boxes.

I wonder if they values change in the angular controller as they change in the html? It'd be nice if we could console.log ctrl.person in our controller...

Maybe when we click a button?

There's an angular directive for this! its called ng-click

add it to a button in your html. What should it be bound to though? Probably not a property because we actually want it to do something. What do you all think?

If you said a function you're right!

  <button ng-click="homeCtrl.logger()">Log it!</button>

Now write the function in your controller and bind it to the controller

ctrl.logger = logger;
function logger() {
  console.log(ctrl.person);
}

##Wrapping up! Thats it! we've learned how to manipulate the users input in our javascript without any of the messy hassles that we had before.

Imaging what we could do with this data now, send it to our own server, send it to an external API, add it to an array, the skys the limit and angular makes it easy!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment