Angularjs Controller 间通信机制
<!DOCTYPE html> <html> <head> <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> <meta charset="utf-8" /> <title>angularjs</title> </head> <body> <div ng-app="app" ng-controller="parentCtr"> <div ng-controller="childCtr1">name : <button ng-click="chance()">get</button> <input ng-model="name" type="text" ng-change="change(name);" /> </div> <div ng-controller="childCtr2">Ctr1 name: <input ng-model="ctr1Name" /> </div> </div> </body> </html> <script> angular.module("app", []).controller("parentCtr", function($scope) { $scope.$on('Ctr1NameChange', function(even, msg) { console.log("ctr1:" + msg[0].Name); $scope.$broadcast("Ctr1NameChangeFromParrent", msg); }); }).controller("childCtr1", function($scope, demoService) { $scope.chance = function(){ demoService.change().success(function(resp){ console.log("sites:" + resp.sites); $scope.name = resp.sites; $scope.$emit("Ctr1NameChange", $scope.name); }); }; /*$scope.change = function(name) { console.log("childCtr1", name); $scope.$emit("Ctr1NameChange", name); };*/ }).controller("childCtr2", function($scope) { $scope.$on("Ctr1NameChangeFromParrent", function(event, msg) { console.log("msg[0]"+msg[0].Name) $scope.ctr1Name = msg; }); }).service('demoService', function($http){ this.change = function(){ console.log('123'); return $http({ method: 'get', url: 'json/demo.json' }).success(function(resp){ console.log(resp.sites); }).error(function(data){ console.log("请求失败"); }); }; }); </script>
{ "sites": [ { "Name": "菜鸟教程", "Url": "www.runoob.com", "Country": "CN" }, { "Name": "Google", "Url": "www.google.com", "Country": "USA" }, { "Name": "Facebook", "Url": "www.facebook.com", "Country": "USA" }, { "Name": "微博", "Url": "www.weibo.com", "Country": "CN" } ] }
今天做项目的时候,这样就没用,回来写个demo就有用,真是醉了。