一、定义2个控制器
<html ng-app="lesson" >
<div ng-controller="Ctrl1">
{{Name}}
</div>
<div ng-controller="Ctrl2">
{{Name}}
</div>
<script src=”scripts/angular-1.1.1.min.js“></script>
<script>
var app = angular.module("lesson",[]);
app.controller("Ctrl1",function($scope){
$scope.Name="控制器1";
})
app.controller("Ctrl2",function($scope){
$scope.Name="控制器2";
})
</script>
二、控制器基于继承的方式通讯(放在控制器内部)
<html ng-app="lesson" >
<div ng-controller="MomCtrl">
{{Name}}
{{Location}}
<button ng-click="ChangeHouse()">换房子</button>
<div ng-controller="MeCtrl">
{{Name}}
{{Location}}
</div>
</div>
<script src=”scripts/angular-1.1.1.min.js“></script>
<script>
var app = angular.module("lesson",[]);
app.controller("MomCtrl",function($scope){
$scope.Name="我是大伟他妈";
$scope.Location = "幸福屯一组51号"
$scope.ChangeHouse = function(){
$scope.Location = "光荣街道69号202室"
}
})
app.controller("MeCtrl",function($scope){
$scope.Name="我是大伟";
})
</script>
三、控制器基于事件的方式通讯
<html ng-app="lesson" >
<div ng-controller="MomCtrl">
{{Name}}<br/>
{{Location}}<br/>
<button ng-click="ChangeHouse()">换房子</button><br/>
<div ng-controller="MeCtrl">
{{Name}}<br/>
{{Location}}<br/>
{{Mobile}}<br/>
</div>
<div ng-controller="GFCtrl">
{{Name}}<br/>
{{Mobile}}<br/>
<button ng-click="Call()">打电话</button>
</div>
</div>
<script src=”scripts/angular-1.1.1.min.js“></script>
<script>
var app = angular.module("lesson",[]);
app.controller("MomCtrl",function($scope){
$scope.Name="我是大伟他妈";
$scope.Location = "幸福屯一组51号"
$scope.ChangeHouse = function(){
$scope.Location = "光荣街道69号202室"
$scope.$on("callDaWei",function(){//收到消息
$scope.$broadcast("yourGfCall") // $broadcast 下发
});
}
})
app.controller("MeCtrl",function($scope){
$scope.Name="我是大伟";
$scope.Mobile = "待机"
$scope.$on("yourGfCall",function(){ // $on 接收
$scope.Mobile = "GF来电"
})
})
app.controller("GfCtrl",function($scope){
$scope.Name="我是大伟的女朋友";
$scope.Mobile = "待机"
$scope.Call = function(){
$scope.Mobile = "呼叫大伟"
$scope.$emit("callDaWei") //向父级传消息 // $emit 上传
}
})
</script>