English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Summary of Differences Between $scope and $rootScope in AngularJS

In a nutshell:

     $rootScope takes effect in the global scope

     $scope only takes effect in the current controller scope

Use the following example to prove the above statement:

Define a module named myApp

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

Create two controllers, oneController and twoController

oneController passes $scope and $rootScope

myApp.controller('oneController', ['$scope', '$rootScope', function ($scope, $rootScope) {
 // Local variables are only displayed in the oneController.
 $scope.one_language = 'Python';
 // Global variables, can be called
 $rootScope.language = 'Go';
});

twoController only passes $scope

myApp.controller('twoController', ['$scope', function ($scope) {
 // Local variables, only displayed in twoController
 $scope.two_language = 'Java';
});

HTML tag content

<span ng-app="myApp">
  <style>
    div{margin-top: 15px;border: 2px solid rebeccapurple;width: 400px;}
  </style>
  <div>
    <h3>I am the global variable language: {{ language}}</h3>
  </div>
  <div ng-controller="oneController">
    <h3>I am the local variable one_language: {{ one_language}}</h3>
  </div>
  <div ng-controller="twoController">
    <h1>twoController</h1>
    <h3>I am the local variable two_language: {{ two_language }}</h3>
    <h3>I am the local variable one_language: {{ one_language}}</h3>
    <h3>I am the global variable language: {{ language }}</h3>
  </div>
</span>

The displayed result

Summary

That is all the content of this article, please carefully read the code above, which will help you understand. If you have any questions, you can leave a message for communication, thank you for your support of the呐喊 tutorial.

You May Also Like