angularJS平行控制器间共享数据

时间:2021-07-06 17:57:38
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-app="myApp">
<div ng-controller="c1">
{{name}} , {{msg}} , {{datas}}
</div>
<div ng-controller="c2">
{{name}} , {{msg}} , {{datas}}
</div>
</body>
<script src="angular.js"></script>
<script>
var app = angular.module("myApp",[]);
//factory和service的最大区别就是service所注入的类型必须为对象而factory可以是任意类型(他们通常用来通过$http进行远程加载数据后分享给控制器)
app.factory('custData1',function(){
return{
message:"共享数据!",
Data:['a','b','c']
}
});
app.controller("c1", function($scope,custData1){
$scope.name="123";
$scope.msg = custData1.message;
$scope.datas = custData1.Data[1];
});
app.controller("c2", function($scope,custData1){
$scope.name="456";
$scope.msg = custData1.message;
$scope.datas = custData1.Data[2];
});
</script>
</html>