是否有可能让一个控制器使用另一个?
例如:
此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
和访问服务.
我有服务,说:
factory('aService', ['$rootScope', '$resource', function ($rootScope, $resource) {
var service = {
foo: []
};
return service;
}]);
Run Code Online (Sandbox Code Playgroud)
我想foo
用来控制用HTML呈现的列表:
<div ng-controller="FooCtrl">
<div ng-repeat="item in foo">{{ item }}</div>
</div>
Run Code Online (Sandbox Code Playgroud)
为了让控制器检测何时aService.foo
更新,我将这个模式拼凑在一起,我将aService添加到控制器$scope
,然后使用$scope.$watch()
:
function FooCtrl($scope, aService) {
$scope.aService = aService;
$scope.foo = aService.foo;
$scope.$watch('aService.foo', function (newVal, oldVal, scope) {
if(newVal) {
scope.foo = newVal;
}
});
}
Run Code Online (Sandbox Code Playgroud)
这感觉很长,我一直在每个使用服务变量的控制器中重复它.有没有更好的方法来完成观察共享变量?