AngularJS JavaScript

AngularJS – Controller with JSON Data

AngularJS – Controller with JSON Data

AngularJS controllers are JavaScript functions that provide data and behavior to a view. One common pattern is to define JSON data directly inside a controller — useful for small, static datasets or for prototyping before connecting to a real REST API. This tutorial shows how to create a controller that exposes a JSON product list to the HTML view.

AngularJS Concepts Used

  • ng-app — declares the AngularJS application boundary
  • ng-controller — attaches a controller to a section of the DOM
  • $scope — the bridge between controller and view
  • ng-repeat — loops over an array and renders a template for each item
  • {{ expression }} — data binding, renders the value of a scope variable

Example: Product List from JSON in Controller

<!DOCTYPE html>
<html ng-app="productApp">
<head>
  <meta charset="UTF-8">
  <title>AngularJS – Controller with JSON Data</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>
  <style>
    body      { font-family: Arial, sans-serif; padding: 20px; }
    table     { border-collapse: collapse; width: 100%; }
    th, td    { border: 1px solid #ccc; padding: 8px 12px; text-align: left; }
    th        { background-color: #0F83A0; color: #fff; }
    tr:nth-child(even) { background-color: #f4f4f4; }
  </style>
</head>
<body>

  <div ng-controller="ProductController">
    <h2>Product List</h2>
    <p>Total products: {{ products.length }}</p>

    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Price (₹)</th>
          <th>Category</th>
          <th>In Stock</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="p in products">
          <td>{{ p.id }}</td>
          <td>{{ p.name }}</td>
          <td>{{ p.price | number:2 }}</td>
          <td>{{ p.category }}</td>
          <td>{{ p.inStock ? 'Yes' : 'No' }}</td>
        </tr>
      </tbody>
    </table>

    <!-- Filter by category -->
    <h3>Filter by Category</h3>
    <input type="text" ng-model="searchCategory" placeholder="Type a category...">
    <ul>
      <li ng-repeat="p in products | filter:{category: searchCategory}">
        {{ p.name }} – ₹{{ p.price }}
      </li>
    </ul>
  </div>

  <script>
    var app = angular.module('productApp', []);

    app.controller('ProductController', function($scope) {

      // JSON data defined directly in the controller
      $scope.products = [
        { id: 1, name: 'Laptop',      price: 75000, category: 'Electronics', inStock: true  },
        { id: 2, name: 'Smartphone',  price: 25000, category: 'Electronics', inStock: true  },
        { id: 3, name: 'Tablet',      price: 35000, category: 'Electronics', inStock: false },
        { id: 4, name: 'Monitor',     price: 15000, category: 'Electronics', inStock: true  },
        { id: 5, name: 'Keyboard',    price:  2500, category: 'Accessories', inStock: true  },
        { id: 6, name: 'Mouse',       price:  1500, category: 'Accessories', inStock: true  },
        { id: 7, name: 'Headphones',  price:  8000, category: 'Audio',       inStock: false }
      ];

      $scope.searchCategory = '';
    });
  </script>
</body>
</html>

How It Works

  1. ng-app="productApp" bootstraps the AngularJS app on the <html> element.
  2. ng-controller="ProductController" creates a new scope and runs the controller function, attaching products and searchCategory to $scope.
  3. ng-repeat="p in products" iterates the array, creating one <tr> per product. The variable p represents each item.
  4. {{ p.price | number:2 }} — the number filter formats the price with 2 decimal places.
  5. ng-model="searchCategory" binds the input to the scope, and filter:{category: searchCategory} applies live filtering.

Useful ng-repeat Variables

Variable Value
$index Current loop index (0-based)
$first true for the first item
$last true for the last item
$even / $odd Alternating row styling

Example: Row Numbers with $index

<tr ng-repeat="p in products">
  <td>{{ $index + 1 }}</td>   <!-- row number -->
  <td>{{ p.name }}</td>
  <td>{{ p.price }}</td>
</tr>

Next Step: Load JSON from a REST API

In production, JSON data comes from a server endpoint rather than being hardcoded. Replace the inline array with an $http call:

app.controller('ProductController', function($scope, $http) {
    $http.get('/api/products')
         .then(function(response) {
             $scope.products = response.data;
         });
});

Summary

An AngularJS controller connects JSON data to the HTML view via $scope. Data binding with {{ expression }} and ng-repeat eliminates manual DOM manipulation — AngularJS updates the view automatically whenever the data changes. Start with hardcoded JSON in the controller for prototyping, then replace it with $http calls to a real REST endpoint. The view code stays identical either way.

Topics: AngularJS JavaScript
← Newer Post Older Post →

Comments

https://www.blogger.com/comment/frame/6690124484600543990?po=3508964186343475872&hl=en&saa=85391&origin=https://www.java9r.com