📕
SEIRFX
  • Introduction
  • About These Notes
  • Schedule
  • Unit 2
    • Node
      • Internet Fundamentals
      • Full-Stack Fundamentals
      • Intro to Node
      • Node Modules
      • Node Packages
    • Express
      • Intro to Express
      • Routes
      • Routes Lab
      • Views
      • Templates
      • Layouts & Controllers
    • CRUD & REST
      • GET & POST
      • GET & POST Lab
      • PUT & DELETE
    • API Calls in Express
      • Axios
      • Request (no longer maintained)
    • Sequelize
      • Terminology
      • Setup
      • Using Models
      • Seeding Data
      • Validations and Migrations
      • Resources
      • 1:M Relationships
      • N:M Relationships
    • Express Authentication
      • Research Components
      • Code Components
      • Auth in Theory
        • Sessions
        • Passwords
        • Middleware
        • Hooks
      • Auth in Practice
        • Create the User
        • User Signup
        • Sessions
        • User Login
        • Authorization and Flash messages
  • Development Workflow
    • Command Line
      • The Terminal
      • Filesystem Navigation
      • File Manipulation
      • Additional Topics
    • Intro to Git
      • Version Control
      • Local Git
      • Remote Git
      • Git Recipes
    • Group Collaboration
      • Git Workflows
      • Project Roles and Tools
    • VS Code Tips & Tricks
  • HTML/CSS
    • HTML
    • CSS Selectors
    • CSS Box Model and Positioning
      • Box Model
      • Display and Positioning
      • Flexbox
      • Grid
      • Flexbox & Grid Games
      • Floats and Clears
      • Additional Topics
    • Advanced CSS
      • Responsive Design
      • Pseudo-Classes/Elements
      • Vendor Prefixes
      • Custom Properties
      • Additional Topics
    • Bootstrap
    • CSS Frameworks
    • Accessibility
  • JavaScript
    • Primitives
    • Arrays
    • Objects
      • Objects Lesson
      • Objects quick guide
      • Object-ception
    • Control Flow
      • Boolean Expressions
      • Conditionals
      • Loops
      • Promises
    • Functions
      • Scope
      • Callbacks
      • Higher Order Functions
      • Callbacks Review Lab
      • Timing Functions
      • Iterators
      • Combining Data Types
      • Combining Data Types Lab
    • Javascript in the browser
      • DOM and Events
      • DOM Manipulation
      • DOM Review
      • DOM Review Lab
      • HP DOM Lab
      • Programmatic DOM Manipulation
      • Grids & Pyramids
      • DOM & Data
      • DOM Events
      • Color Palette Picker
      • Sketchpad
    • HTML5 Canvas
    • How To Reduce Redundancy
    • OOP
      • Westworld Lab
      • OOP Factories
      • OOP Inheritance
      • OOP Inheritance Lab
      • Tomagotchi Lab
      • OOP Space Battle
      • OOP Snowman
      • (2019) JavaScript OOP
      • (2016) OOP with Classes
      • (1995) OOP with Prototypes
      • Constructors
      • Prototypes
    • Intro to TDD
    • Scoping
    • Inheritance
      • Prototypal Inheritance
      • Call, Apply, and other Functions
      • ES6 Inheritance
      • Resources
    • Custom Node Modules
    • Additional Topics
      • AJAX, Fetch, and Async/Await
      • AJAX w/JSON and Localstorage
        • AJAX w/JSON
        • Local Storage
      • Async module
      • Data Scraping
  • jQuery
    • Intro
      • DOM Manipulation
      • Reddit Practice
      • Styling
      • Events
    • Plugins
    • AJAX
  • APIs
    • Fetch
    • AJAX w/jQuery
    • AJAX w/Fetch
  • Databases
    • Intro to SQL
    • Advanced SQL
    • MongoDB
      • Intro to NoSQL
      • CRUD in MongoDB
      • Data Modeling
      • Intermediate Mongo
  • Left over Node/Express
    • Testing with Mocha and Chai
    • Mongoose
      • Mongoose Associations
    • JSON Web Tokens
      • Codealong
    • Additional Topics
      • oAuth
      • Geocoding with Mapbox
      • Geocoding and Google Maps
      • Cloudinary
      • Websockets with Socket.io
      • SASS
  • Ruby
    • Intro to Ruby
    • Ruby Exercises
    • Ruby Classes
    • Ruby Testing with Rspec
    • Ruby Inheritance
    • Ruby Data Scraping
  • Ruby on Rails
    • Intro to Rails
    • APIs with Rails
    • Asset Pipeline
    • Rails Auth and 1-M
      • Auth Components
    • Rails N:M
    • ActiveRecord Polymorphism
    • Additional Topics
      • oAuth
      • SASS
      • Rails Mailers
      • Cloudinary
      • Jekyll
  • React (Updated 2019)
    • ES6+/ESNext
      • Const and Let
      • Arrow Functions
      • Object Literals and String Interpolation
      • ES6 Recap
      • ES6 Activity
    • Intro to React
      • Create React App
      • Components and JSX
      • Virtual DOM
      • Props
      • Dino Blog Activity
      • Nested Components
      • Lab: LotR
    • React State
      • Code-Along: Edit Dino Blog
      • Lab: Simple Calc
      • Lifting State
    • React Router
      • Browser History/SPAs
      • React Router (lesson and full codealong)
      • Router Lab
    • Fetch and APIs
      • APIs with Fetch and Axios
      • Fetch the Weather
    • React Hooks
    • React LifeCycle
      • Lab: Component LifeCycle
    • React Deployment
    • Additional Topics
      • React Frameworks
        • Material UI Theming
      • Typescript
        • More Types and Syntax
        • Tsconfig and Declaration Files
        • Generics with Linked List
      • Redux
      • TypeScript
      • Context API
      • React Native
  • Meteor
  • Deployment and Config
    • Installfest
      • Mac OSX
      • Linux
      • Git Configuration
      • Sublime Packages
    • Deploy - Github Pages
    • Deploy - Node/Sequelize
    • Deploy - Node/MongoDB
    • Deploy React
    • Deploy - Rails
      • Foreman (Environment Variables)
    • Deploy - AWS Elastic Beanstalk
    • Deploy - S3 Static Sites
    • Deploy - Django
    • Deploy - Flask
  • Data Structures and Algorithms
    • Recursion
    • Problem Solving - Array Flatten
    • Binary Search
    • Algorithm Complexity
    • Stacks and Queues
    • Bracket Matching
    • Ruby Linked Lists
      • Sample Code
      • Beginner Exercises
      • Advanced Exercises
    • JS Linked Lists
      • Sample Code
      • Beginner Exercises
      • Beginner Solutions
    • Hash Tables
    • Intro to Sorting
    • Insertion Sort
    • Bucket Sort
    • Bubble Sort
    • Merge Sort
    • Quick Sort
    • Heap Sort
    • Sorting Wrapup
    • Hashmaps
    • Trees and Other Topics
  • Python
    • Python Installation
    • Intro to Python
    • Python Lists
    • Python Loops
    • Python Dictionaries
    • Python Sets and Tuples
    • Python Cheatsheet
    • Python Functions
    • Python Classes
    • Python Class Inheritance
    • Intro to Flask
    • Intro to SQLAlchemy
      • Flask and SQLAlchemy
    • Using PyMongo
    • Intro to Django
    • CatCollector CodeAlong
      • URLs, Views, Templates
      • Models, Migrations
      • Model Form CRUD
      • One-to-Many Relations
      • Many-to-Many Relations
      • Django Auth
    • Django Cheatsheet
    • Django Auth
    • Django Polls App Tutorial
    • Django School Tool Tutorial
    • Django 1:M Relationships
    • Custom Admin Views
    • Data Structures and Algorithms
      • Recursion
      • Binary Search
      • Stacks and Queues
      • Linked Lists
      • Binary Trees
      • Bubble Sort
      • TensorFlow & Neural Networks
    • Adjacent Topics
      • Raspberry Pi
      • Scripting
  • Assorted Topics
    • History of Computer Science
    • Regular Expressions
    • Being Successful in SEI
    • Internet Fundamentals
      • Internet Lab
    • Adjacent Workflow
      • UX/UI
      • Wireframing Exercise: Build an Idea
      • Agile
    • Post SEI
      • Learning Resources
      • Deliverables -> Portfolio
      • FAQ
  • Projects
    • Project 1
    • Project 2
    • Project 3
      • Project 3 Pitch Guidelines
    • Project 4
    • Past Projects
      • Project 1
      • Project 2
      • Project 3
      • Project 4
      • Portfolios
    • Post Project 2
    • MEAN Hackathon
      • Part 1: APIs
      • Part 2: Angular
    • Portfolio
  • Web Development Trends
  • Resources
    • APIs and Data
    • Tech Websites
    • PostgreSQL Cheat Sheet
    • Sequelize Cheat Sheet
    • Database Administration
  • Archived Section
    • (Archived) ReactJS
      • Intro to React
        • Todo List Codealong
        • Additional Topics
      • Deploy React
      • React with Gulp and Browserify
        • Setting up Gulp
        • Additional Gulp Tasks
      • React Router
        • OMDB Router
        • OMDB Search
        • Additional Resources
      • React Animations
        • CSS Animations
    • AngularJS
      • Intro to AngularJS
        • Components and SPA
        • Create an Angular App
      • Angular Directives and Filters
      • Angular Animation
      • Angular Bootstrap Directives
        • Bootstrap Modals
      • Angular $http
      • Angular Services
        • Service Recipes
        • ngResource
        • Star Wars Codealong
      • Angular Routing
      • Angular + Express
      • Angular Authentication
        • Additional Topics
      • Angular Components
      • Angular Custom Filters
      • Angular Custom Directives
Powered by GitBook
On this page
  • Basic Angular Setup - Modules, Controllers, Views
  • Create an Angular controller
  • Scope
  • Initializing scope
  • Load the controller on a page
  • Two-way data binding
  • ng-model
  • Handling user events
  • ng-click
  • Controllers Instantiate Data
  • Conclusion

Was this helpful?

  1. Archived Section
  2. AngularJS
  3. Intro to AngularJS

Create an Angular App

PreviousComponents and SPANextAngular Directives and Filters

Last updated 4 years ago

Was this helpful?

Basic Angular Setup - Modules, Controllers, Views

Like a few frameworks we've seen, there's not a particular way to organize your application to make Angular work. We'll have to create our own, but let's try to keep it standard.

In your starter folder, you'll see some empty files and a couple of folders.

First, let's get Angular from and paste into script tag in the <head></head>

 <head>
   <meta charset="utf-8">
   <title>Intro to Angular</title>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
 </head>

Now, we set up a module. Go to your app.js file, and all it takes is this little line:

// Define a new module. The first argument is what we want to call our app, the second is an array of dependencies (which we don't need at the moment, so there are none)
var introApp = angular.module('IntroToAngularApp', []);

This sets our app up. It's important to include that array when defining a module, even if there are no dependencies – that tells Angular we're initializing a module.

Now, back in our HTML, make sure your app.js is included in a script tag, and add an ng-app directive in the <html> tag.

<!DOCTYPE html>
<html ng-app="IntroToAngularApp">
  <head>
    <meta charset="utf-8">
    <title>Intro to Angular</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
    <script src="js/app.js"></script>
  </head>

Since we defined it in app.js with a name of IntroToAngularApp, we just reference what we named it here. This tells the HTML to use that module.

Now, let's just check to make sure it worked. If it worked correctly, we should be able to put some simple expression in our HTML, and Angular will render it.

<body>
{{ 1 + 1 }}
</body>

If Angular's working, it'll add our numbers together and spit out a 2 on the page – that's how templating works in Angular, inside curly brackets.

Open it up in a browser to check. And remember – if it doesn't work, check your browser's console for errors!

Create an Angular controller

So, in Angular's flavor of MVC, controllers are intended to primarily:

  1. Respond to user actions.

  2. Provide data to the view (occasionally referred to the view-model).

Now, lets stub out a new controller and plug it into our module:

Let's place the following in app.js

introApp.controller('HomeCtrl', ['$scope', function($scope) {

}]);

Pretty much everything you do in Angular will depend on a controller. You can add a controller to your module using the controller method which takes 2 parameters.

  • Name of the controller

  • An array containing the dependencies and initialization function for this controller.

Scope

The scope (represented in Angular as $scope) is where you will store all of your data in a controller. Any data stored in the scope will be available in the view within the DOM object that has the ng-controller directive.

Dependency Injection

To access the $scope object we need to inject it as a dependency. This is done by including it as a string in the array before the function AND defining it as a parameter within the function.

You can load as many dependencies as you want, but it is vital that the strings in the array are in the same order as the parameter in the function.

introApp.controller('HomeCtrl', ['$scope', '$http', function($scope, $http) {

}]);

In the above example we load $scope and $http. Notice the strings $scope and $http and the 2 parameters $string and $http. The strings tell it what to load and the parameters are how you access it within the function. This is done because the variables names can end up changing during JavaScript minification. You can technically name the parameters (in the function) whatever you want, but it's good practice to name them they same as the dependency that you are loading.

Side note: $http is the angular http (ajax) module. We'll learn about that later. It is just used above to demonstrate how to load multiple dependencies.

Initializing scope

Once you load the $scope dependency you just use it like any other object. You can define whatever keys you want and assign them any value. the value will then be available in the view.

introApp.controller('HomeCtrl', ['$scope', function($scope) {
  $scope.name = 'Bill Murray';
}]);

Load the controller on a page

Controllers can be attached to DOM elements using the ng-controller directive.

<div ng-controller="HomeCtrl"></div>

Then you can reference variables attached to $scope in the view like this:

<div ng-controller="HomeCtrl">
  Hello, {{name}}
</div>

Two-way data binding

Angular uses two-way data binding. This means that if any data in $scope is changed in the controller, it is reflected in the view AND if the data is changed in the view, it is updated in the controller.

ng-model

The easiest way to achieve two-way data binding is using the ng-model directive. ng-model can be used on any form element and creates a two-way data binding to the value of the $scope key specified.

Expanding on the example above (same controller code) you can do the following...

<div ng-controller="HomeCtrl">
  Hello, {{name}}
  <input type="text" ng-model="name">
</div>

Now if the user types something into the input box, $scope.name will be updated in the controller, which also means the {{name}} will be updated to match.

Handling user events

Angular can also handle user events using other directives. One of the most common directives is ng-click.

ng-click

To detect a click event we use the ng-click directive and give it a function to call when the user clicks an element. This function is attached to the $scope just like a value.

introApp.controller('HomeCtrl', ['$scope', function($scope) {
  //default
  $scope.happy = false;

  //toggle function
  $scope.toggleHappy = function() {
    $scope.happy = !$scope.happy;
  }
}]);
<button ng-click="toggleHappy()">Toggle Happy</button>
<p>{{happy}}</p>

clicking the button will cause happy to switch $scope.happy true to false.

Alternatively, you can put any code directly in the ng-click, but it is generally smart to use functions instead. However, for simple one-liners, it's generally OK.

<button ng-click="happy = !happy;">Toggle Happy</button>
<p>{{happy}}</p>

Again, notice that in the controller it is $scope.happy, but in the view (html) it is just happy (without $scope).

Controllers Instantiate Data

As a wrapup to Angular, know that controllers are just functions that can include dependencies and data instantiation. Every time the ng-controller directive is used, a controller is instantiated. To illustrate this, try to copy/paste your controller div and see what happens.

<body>
  <div ng-controller="HomeCtrl">
    Hello, {{name}}
    <input type="text" ng-model="name">

    <div>
      <button ng-click="happy = !happy;">Toggle Happy</button>
      <p>{{happy}}</p>
    </div>
  </div>
  <div ng-controller="HomeCtrl">
    Hello, {{name}}
    <input type="text" ng-model="name">

    <div>
      <button ng-click="happy = !happy;">Toggle Happy</button>
      <p>{{happy}}</p>
    </div>
  </div>
</body>

You'll see that each instance of ng-controller has its own set of data. Pretty sweet!

Conclusion

As you can see, the structure of Angular differs significantly from other frontend frameworks we've been using, like jQuery. Take a moment and review:

  • How do you make modules and controllers in Angular?

  • What must we do in order to bootstrap an Angular app to a page?

  • Compare and contrast jQuery and AngularJS in the context of adding a click event.

Google's CDN