Home > Web Front-end > JS Tutorial > How to Share $scope Data Between States in AngularJS Without Services or Watchers?

How to Share $scope Data Between States in AngularJS Without Services or Watchers?

Linda Hamilton
Release: 2024-11-14 10:31:02
Original
486 people have browsed it

How to Share $scope Data Between States in AngularJS Without Services or Watchers?

Sharing $scope Data Among States in AngularJS

Question:

How can $scope data from the parent controller be accessible to child states in AngularJS without using services or parent controller watchers?

Answer:

Understanding Scope Inheritance

In AngularJS, scope properties inherit down the state chain if the state views are nested. Therefore, define the state views as follows:

.state("main", {
      controller:'mainController',
      url:"/main",
      templateUrl: "main_init.html"
  })  
  .state("main.1", {
      controller:'mainController',
      parent: 'main',
      url:"/1",
      templateUrl: 'form_1.html'
  })  
  .state("main.2", {
      controller:'mainController',
      parent: 'main',
      url: "/2",
      templateUrl: 'form_2.html'
  })  
Copy after login

Initializing the Data in the Parent Controller

Instantiate the data in the parent controller as an object with properties, such as:

controller('mainController', function ($scope) {
  $scope.Model = $scope.Model || {Name : "xxx"};
})
Copy after login

Using Dot Notation in ng-model

Ensure prototypal inheritance by using dot notation in ng-model, e.g.:

<input type="text" ng-model="Model.Name">
Copy after login

Example:

See a working example in this Plunker: https://plnkr.co/edit/jmEb62e96kHlXPjLGBb9?p=preview

The above is the detailed content of How to Share $scope Data Between States in AngularJS Without Services or Watchers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template