正在做的项目有一个需求,就是需要从homeController拿到数据传到另一个myotherController里面去。
比如这个数据为$scope.homedata="imhomedatacanyouseeme?";
1.使用instance,
// 全局对象instance
app.factory('instance', function () {
var instance = {}
return instance;
});
2.根据网上查来的资料使用$scope的冒泡和隧道机制,$broadcast会把事件广播给所有的子controller,在父controller中使用$emit获取该事件冒泡,$on则是angularjs的时间注册函数。
parentController:
$scope.$on("homeDataToMyother",function (event, data) {
console.log("parent", data);
$scope.$broadcast("homeToMyother", data);
});
homeController:
$scope.goToMyother = function(){
//拿到home的数据传给关怀提醒
$scope.homedata="imhomedatacanyouseeme?";
$scope.$emit("homeDataToMyother", $scope.homeData);//传给parentControll
$scope.go('/myother');
}
myotherController:
$scope.$on("homeToMyother",function (event, data) {
console.log("myother", data);
});
控制台输出:
parentimhomedatacanyouseeme?
myotherunderfine //没有拿到这个数据
然而我的项目结构不是所有controller都写在一个js里面的,而是每个controller都有自己单独的js,使用$on没有取到$broadcast广播的事件以及它的数据。然后我就使用了$parent。
parentController:
$scope.$on("homeDataToMyother",function (event, data) {
console.log("parent", data);
$scope.$parent.myHomeData = data;
console.log($scope.$parent.myHomeData);
});
myotherController:
console.log($scope.$parent.myHomeData);
控制台输出:
parentimhomedatacanyouseeme?
imhomedatacanyouseeme?