</>
Skip to content
AngularJS lessons (7/28)

AngularJS — Scope

What is Scope?

Scope is an object that connects controller and view.

app.controller('MyController', function($scope) {
  $scope.name = 'John';
  $scope.items = ['Item 1', 'Item 2', 'Item 3'];
});

Scope Properties

$scope.user = {
  name: 'John',
  age: 30,
  address: {
    city: 'New York',
    state: 'NY'
  }
};

Scope Methods

$scope.sayHello = function() {
  return 'Hello, ' + $scope.user.name;
};

Scope Hierarchy

Root Scope
├── Parent Controller Scope
│   ├── Child Controller Scope 1
│   └── Child Controller Scope 2
└── Another Parent Scope

Scope Events

// Emit event
$scope.$emit('myEvent', data);

// Broadcast to children
$scope.$broadcast('myEvent', data);

// Listen
$scope.$on('myEvent', function(event, data) {
  console.log(data);
});

Watchers

$scope.$watch('name', function(newVal, oldVal) {
  console.log('Name changed from', oldVal, 'to', newVal);
});

Mini Practice

  1. Create scope properties
  2. Add methods to scope
  3. Use scope events
  4. Implement watchers

Up Next

Continue with Data Binding — two-way data binding.

Related Topics

Frequently Asked Questions about Scope

What is Scope in AngularJS?

Scope is a fundamental concept in AngularJS. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Scope?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Scope.

Why is Scope important in AngularJS?

Scope is essential for AngularJS development. Understanding this concept will help you write better code and solve real-world problems more effectively.