Cha*_*cho 9 angularjs angularjs-scope angularjs-module
我最近开始使用AngularJS,现在我正在构建我的应用程序的方式是这样的:
var app = angular.module('app', ['SomeController', 'MainController']);
app.controller('MainController', function ($scope) {
// do some stuff
}
Run Code Online (Sandbox Code Playgroud)
var SomeController= angular.module('SomeController', []);
SomeController.controller('SomeController', function ($scope) {
$scope.variable = "test";
// do some otherstuff
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是模块之间没有共享范围.从MainController我不能得到变量"test"例如.
$scope在它们之间共享,或者可以将所有内容放在一个控制器中?m59*_*m59 19
你可以使用这样的服务:在这里现场演示(点击).
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;
});
Run Code Online (Sandbox Code Playgroud)
标记:
<div ng-controller="otherCtrl">
<input ng-model="shared.someData" placeholder="Type here..">
</div>
<div ng-controller="myCtrl">
{{shared.someData}}
</div>
Run Code Online (Sandbox Code Playgroud)
您还可以嵌套控制器以使子控制器继承父控制器的作用域属性: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>
Run Code Online (Sandbox Code Playgroud)
但是,孩子不会更新父母 - 只有父母的属性更新孩子.
您可以使用"点规则"让孩子的更新影响父母.这意味着将属性嵌套在对象中.由于父级和子级都具有相同的对象,因此该对象的更改将反映在两个位置.这就是对象引用的工作方式.很多人认为不使用继承是最佳实践,但是将所有内容放在具有隔离范围的指令中.