加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS模块/范围共享

发布时间:2020-12-17 09:17:48 所属栏目:安全 来源:网络整理
导读:我最近开始使用AngularJS,现在我正在构建我的应用程序是这样的: MainController.js var app = angular.module('app',['SomeController','MainController']);app.controller('MainController',function ($scope) { // do some stuff} SomeController.js var
我最近开始使用AngularJS,现在我正在构建我的应用程序是这样的:

MainController.js

var app = angular.module('app',['SomeController','MainController']);

app.controller('MainController',function ($scope) {
    // do some stuff
}

SomeController.js

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

SomeController.controller('SomeController',function ($scope) {
    $scope.variable = "test";
    // do some otherstuff
}

我所遇到的问题是模块之间没有共享范围.从MainController我不能得到变量“test”为例.

>这是最好的做法是什么?我将所有的控制器存储在1个文件中的1个模块中?
>我如何拥有2页的2个控制器,并共享它们之间的$范围,或者可以把所有东西放在一个控制器?

你可以使用像这样的服务: Live demo here (click).

JavaScript的:

var otherApp = angular.module('otherApp',[]);
otherApp.factory('myService',function() {
  var myService = {
    someData: ''
  };
  return myService;
});
otherApp.controller('otherCtrl',function($scope,myService) {
  $scope.shared = myService;
});


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

app.controller('myCtrl',myService) {
  $scope.shared = myService; 
});

标记:

<div ng-controller="otherCtrl">
    <input ng-model="shared.someData" placeholder="Type here..">
  </div>
  <div ng-controller="myCtrl">
  {{shared.someData}}
  </div>

Here’s a nice article on sharing data with services.

您还可以嵌套控制器以使父控件的范围属性由子范围继承: http://jsbin.com/AgAYIVE/3/edit

<div ng-controller="ctrl1">
    <span>ctrl1:</span>
    <input ng-model="foo" placeholder="Type here..">
    <div ng-controller="ctrl2">
      <span>ctrl2:</span>
      {{foo}}
    </div>
  </div>

但是,孩子不会更新父级 – 只有父级的属性才能更新子级.

您将使用“点规则”来更新子项影响父级.这意味着将属性嵌套在对象中.由于父和子都具有相同的对象,因此该对象上的更改将反映在两个地方.这就是对象引用的工作原理.很多人认为最好的做法是不使用继承,而是把所有内容都放在具有隔离范围的指令中.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读