首頁 >web前端 >js教程 >如何在沒有服務或觀察者的情況下在 AngularJS 中的狀態之間共享 $scope 資料?

如何在沒有服務或觀察者的情況下在 AngularJS 中的狀態之間共享 $scope 資料?

Linda Hamilton
Linda Hamilton原創
2024-11-14 10:31:02519瀏覽

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

在AngularJS 中的狀態之間共享$scope 數據

問題:

$ scope 如何AngularJS 中的子狀態可以存取來自父控制器的數據,而無需使用服務或父控制器觀察者?

答案:

理解作用域繼承

在AngularJS 中,作用域屬性沿著狀態鏈繼承,如果狀態視圖是嵌套的。因此,定義狀態視圖如下:

.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'
  })  

初始化父控制器中的資料

將父控制器中的資料實例化為具有屬性的對象,例如:

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

在中使用點表示法ng-model

透過在ng-model 中使用點表示法確保原型繼承,例如:

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

範例:

請參考這個Plunker 中的一個工作範例: https://plnkr.co/edit/jmEb62e96kHlXPjLGBb9?p=preview

以上是如何在沒有服務或觀察者的情況下在 AngularJS 中的狀態之間共享 $scope 資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:Nodejs 自訂 CORS下一篇:Nodejs 自訂 CORS