angularjs:使用服务在控制器之间进行通信 [英] angularjs: using service to communicate between controllers
问题描述
我的控制器中注入了一项服务.该服务定义了许多功能.
I have a service that is injected in my controllers. The service defines a number of functions.
现在我想向该服务添加一个变量,该变量将在应用程序中保存 selectedItem.我是这样做的:
Now I would like to add a variable to that service that would hold the selectedItem in the application. I've done it this way:
angular.module('myservices', []).
factory('serviceA', function () {
var serviceA= {
selectedItem: selectedItem,
... more functions here
};
return serviceA;
var selectedItem;
... functions go here
});
在我的一个控制器中,我设置了所选项目:
In one of my controllers I set the selected item:
serviceA.selectedItem = someItem;
在另一个控制器中,视图像这样引用所选项目:
and in another controller the view references the selected item like this:
<span>{{serviceA.selectedItem.value}}</span>
跨度永远不会更新,即使 selectedItem 设置正确.我究竟做错了什么 ?
The span is never updated, even though the selectedItem is set correctly. What am I doing wrong ?
推荐答案
要访问视图中的服务,需要将其分配给作用域:
To access the service in your view, you need to assign it to the scope:
$scope.serviceA = serviceA;
这篇关于angularjs:使用服务在控制器之间进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!