是否有可能让一个控制器使用另一个?
例如:
此HTML文档只是打印MessageCtrl控制器在messageCtrl.js文件中传递的消息.
<html xmlns:ng="http://angularjs.org/">
<head>
<meta charset="utf-8" />
<title>Inter Controller Communication</title>
</head>
<body>
<div ng:controller="MessageCtrl">
<p>{{message}}</p>
</div>
<!-- Angular Scripts -->
<script src="http://code.angularjs.org/angular-0.9.19.js" ng:autobind></script>
<script src="js/messageCtrl.js" type="text/javascript"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
控制器文件包含以下代码:
function MessageCtrl()
{
this.message = function() {
return "The current date is: " + new Date().toString();
};
}
Run Code Online (Sandbox Code Playgroud)
这只是打印当前日期;
如果我要添加另一个控制器,DateCtrl它将日期以特定格式交还给MessageCtrl,那怎么会这样做呢?DI框架似乎关注XmlHttpRequests和访问服务.
我正在尝试跨控制器共享数据.用例是一种多步形式,在一个输入中输入的数据稍后用于原始控制器外的多个显示位置.下面的代码和jsfiddle这里.
HTML
<div ng-controller="FirstCtrl">
<input type="text" ng-model="FirstName"><!-- Input entered here -->
<br>Input is : <strong>{{FirstName}}</strong><!-- Successfully updates here -->
</div>
<hr>
<div ng-controller="SecondCtrl">
Input should also be here: {{FirstName}}<!-- How do I automatically updated it here? -->
</div>
Run Code Online (Sandbox Code Playgroud)
JS
// declare the app with no dependencies
var myApp = angular.module('myApp', []);
// make a factory to share data between controllers
myApp.factory('Data', function(){
// I know this doesn't work, but what will?
var FirstName = '';
return FirstName;
}); …Run Code Online (Sandbox Code Playgroud)