AngularJS模块/共享范围 [英] AngularJS Modules/Scope Sharing

查看:98
本文介绍了AngularJS模块/共享范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近使用AngularJS现在我建设我的应用程序的方式是这样开始:

I recently started using AngularJS and the way I'm building my apps now is like this:

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 我不能得到例如变量测试。

The problem that Im' running into is that the scope is not being shared between modules. From MainController I can't get the variable "test" for example.


  • 什么是我们的最佳做法?难道我存储我的所有控制器在1个模块中的1个文件?

  • 我怎么能有2个控制器1页以及它们之间共享 $范围,还是确定把一切都在短短的一个控制器?

  • What is the best practice for this? Do I store all my controllers in 1 module in 1 file?
  • How can i have 1 page with 2 controllers and share the $scope between them, or is it OK to put everything in just one controller ?

推荐答案

您可以使用这样的服务: 现场演示这里(点击)。

You could use a service like this: 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', function($scope, myService) {
  $scope.shared = myService; 
});

标记:

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

这里与服务共享数据的好文章。

您可以还巢控制器有父控制器的作用域属性由子作用域继承: http://jsbin.com/AgAYIVE / 3 /编辑

You can also nest controllers to have the parent controller's scope properties inherited by the child scope: 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>

不过,孩子不会更新父 - 只有父的属性更新子

But, the child won't update the parent - only the parent's properties update the child.

您将使用点规则来对孩子的更新影响父。这意味着,在对象嵌套的属性。因为父母和孩子都具有相同的对象,该对象上的变化将体现在这两个地方。这是对象引用是如何工作的。很多人认为这不使用继承的最佳实践,而是把一切都放在指令孤立范围。

You would use "the dot rule" to have updates on the child affect the parent. That means nesting your properties in an object. Since the parent and child both have the same object, changes on that object will be reflected in both places. That's just how object references work. A lot of people consider it best practice to not use inheritance, but put everything in directives with isolated scope.

这篇关于AngularJS模块/共享范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆