【问题标题】:angularjs multiple controllers on one page一页上的angularjs多个控制器
【发布时间】:2013-11-26 01:49:46
【问题描述】:
【问题讨论】:
标签:
javascript
angularjs
angularjs-scope
controllers
【解决方案2】:
每次你使用 ng-controller 时,你都会创建一个新的控制器实例,它有自己的作用域。如果您在 body 标记(或新的父级)上设置 subCCtrl,并将其从当前所在的两个 div 中删除,它对我有用。
您可能想要研究的其他解决方案是将“hideThisBox”保留在根范围内,在单击保存时广播事件或将其保留在服务中。
【解决方案3】:
您需要在控制器和视图中进行一些更改。
var app = angular.module('plunker', []);
app.controller('subCCtrl', function($scope) {
$scope.hideThisBox = false;
$scope.update = function(label) {
if (label == 'Cost')
$scope.displaybox = true;
else
$scope.displaybox = false;
}
});
app.controller('subACtrl', function($scope) {
});
app.controller('subBCtrl', function($scope) {
});
HTML:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script data-require="angular.js@1.0.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js" data-semver="1.0.8"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="subCCtrl" class="row-fluid">
<div class="span6">
<a href="#" ng-click='update("Cost");displaybox=true;'>Cost</a>
<br />
<a href="#" ng-click='update("Savings");displaybox=fasle;'>Savings</a>
<br />
</div>
<hr />
<div ng-controller="subACtrl">Do stuff that uses subACtrl</div>
<div ng-controller="subBCtrl">Do stuff that uses subBCtrl</div>
<hr />
<div ng-controller="subCCtrl" class="row-fluid">
<div class="span3">
<label>If click on 'Savings', hide below box: </label>
</div>
<div ng-hide="hideThisBox" class="span6">
<input type="text" ng-model="test2" ng-show="displaybox"/>
</div>
</div>
</div>
</body>
</html>
【解决方案4】:
我建议您阅读 Javascript 范围。您的代码的问题是ng-controllers 的范围。
【解决方案5】:
我想你已经得到了答案,但是对于接下来要来的人来说,这里有一些提示^^(希望它会有所帮助):
<div id="maindiv" ng-controller="myCtrl>
<div id="subdiv1">
<div></div>
<div>
<div>some text</div>
</div>
</div>
<div id="subdiv2" ng-controller="myCtrl">
<div>
<span>-</span>
<span>so</span>
<span>this</span>
<span>is</span>
<span>a</span>
<span>subdiv</span>
<span>.</span>
</div>
</div>
</div>
</div>
-
Subdiv1 将具有与 maindiv 相同的范围
- 但 Subdiv2 将拥有自己的 myCtrl 控制器范围实例。
- 在全局范围内,Subdiv2 的作用域应该是来自 maindiv 作用域的数据。
这只是一些简单的提示,您会在 SO 或 google 上找到更多有用的提示,但无论如何,如果它可以帮助你们中的一些人,那就太棒了。