为了在控制器之间共享数据,通常使用服务。
我发现$rootScope.$broadcast
如果我要分享的数据是 a[]
或{}
.
对我来说,使用广播的好处是您不必使用 watcher 来检查数据是否已加载到服务中。编写的代码也更少。
所以我的问题是:
- 是否可以使用 $broadcast
- 使用 $broadcast 是否有一些不便
这是一些使用两种“技术”的示例来说明我的意思。
使用示例 $rootScope.$broadcast
// controller is registering 'list-loaded'
angular.module('myApp').controller(
'ControllerOne'
['$rootScope','$scope',
function ($rootScope, $scope) {
// the data
$scope.data = {
list : ["foo","bar"]
}
// sending the event with the data
$rootScope.$broadcast('list-loaded', { list: $scope.data.list });
}
]
);
//controller is listening for 'list-loaded'
angular.module('myApp').controller(
'ControllerTwo',
['$rootScope','$scope',
function ($rootScope, $scope) {
// empty data
$scope.data = {}
// when the event is received we set the data
$scope.$on('list-loaded', function(event, args) {
$scope.data.list = args.list;
});
}
]
);
使用服务的示例
// the service
angular.module('myApp').factory(
'Service',
[
function() {
// the data to be shared
var list = []
return {
setList : function(pList){
list = pList;
},
getList : function(){
return list;
}
};
}
]
);
//controller is setting list into Service
angular.module('myApp').controller(
'ControllerOne',
['$scope', 'Service',
function ($scope, Service) {
// setting the data to service
Service.setList(["foo","bar"])
}
]
);
//controller is getting list from Service
angular.module('myApp').controller(
'ControllerTwo',
['$scope','Service',
function ($scope, Service) {
// getting the data from service
$scope.data = {
list : Service.getList()
}
}
]
);