AngularJS模块/范围共享

时间:2013-12-23 21:05:44

标签: angularjs angularjs-scope angularjs-module

我最近开始使用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
}

Im'遇到的是模块之间没有共享范围。从 MainController 我无法获得变量" test"例如。

  • 最佳做法是什么?我是否将所有控制器存储在一个文件中的1个模块中?
  • 我如何拥有1个带2个控制器的页面并在它们之间共享$scope,或者将所有内容放在一个控制器中是否可以?

2 个答案:

答案 0 :(得分:19)

您可以使用以下服务: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>

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>

但是,孩子不会更新父母 - 只有父母的属性才会更新孩子。

您可以使用“点规则”让孩子的更新影响父母。这意味着将属性嵌套在对象中。由于父级和子级都具有相同的对象,因此该对象的更改将反映在两个位置。这就是对象引用的工作方式。很多人认为不使用继承是最佳做法,但是将所有内容放在具有隔离范围的指令中。

答案 1 :(得分:0)

您可以使用$rootScope,每个Angular应用程序只有一个根范围。

Reference

app.controller('MainController', function ($scope, $rootScope) {
    $rootScope.data = 'App scope data';
}
相关问题