Roadmap › AngularJS (1.x) — Legacy › Module: Fundamentals
Lessons in this course (13)

1. Module, controller, $scope and two-way binding

Basic★ Must knowLesson 1 of 13
html
<!DOCTYPE html>
<html ng-app="shopApp">
<body ng-controller="OrderController as vm">
  <input ng-model="vm.customer" placeholder="Customer">
  <p>Hello {{ vm.customer }}</p>                         <!-- updates as you type: two-way binding -->
  <ul>
    <li ng-repeat="o in vm.orders | filter:{status:'paid'} | orderBy:'-total' track by o.id">
      #{{ o.id }} — {{ o.total | currency:'₹' }}
    </li>
  </ul>
  <button ng-click="vm.add()" ng-disabled="!vm.customer">Add</button>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.3/angular.min.js"></script>
  <script>
    angular.module("shopApp", [])
      .controller("OrderController", function () {
        const vm = this;                                  // "controller as" syntax (preferred over $scope)
        vm.customer = "";
        vm.orders = [{ id: 1, total: 1200, status: "paid" }, { id: 2, total: 300, status: "pending" }];
        vm.add = () => vm.orders.push({ id: vm.orders.length + 1, total: 500, status: "paid" });
      });
  </script>
</body>
</html>

Two-way binding: ng-model updates the model when the user types, and the view updates when the model changes (via the digest cycle). Controller-as avoids $scope prototype inheritance pitfalls ("always have a dot in ng-model").