基于原型繼承
父類(lèi)的更改會(huì)觸發(fā)所有的子類(lèi),子類(lèi)的修改只會(huì)自身
<div ng-controller="Sandcrawler" ng-app>
<p>Location: {{location}}</p>
<button ng-click="move('Mos Eisley South')">Move</button>
<div ng-controller="Droid">
<p>Location: {{location}}</p>
<button ng-click="sell('Owen Farm')">Sell</button>
</div>
</div>
function Sandcrawler($scope) {
$scope.location = "Mos Eisley North";
$scope.move = function(newLocation) {
$scope.location = newLocation;
}
}
function Droid($scope) {
$scope.sell = function(newLocation) {
$scope.location = newLocation;
}
}
基于事件的方式
on 注冊(cè)事件 并由 emit 觸發(fā)
向上
<div ng-controller="Sandcrawler" ng-app>
<p>Sandcrawler Location: {{location}}</p>
<div ng-controller="Droid">
<p>Droid Location: {{location}}</p>
<button ng-click="summon()">Summon Sandcrawler</button>
</div>
</div>
function Sandcrawler($scope) {
$scope.location = "Mos Eisley North";
$scope.$on('summon', function(e, newLocation) {
$scope.location = newLocation;
});
}
function Droid($scope) {
$scope.location = "Owen Farm";
$scope.summon = function() {
$scope.$emit('summon', $scope.location);
}
}
向下
function Sandcrawler($scope) {
$scope.location = "Mos Eisley North";
$scope.recall = function() {
$scope.$broadcast('recall', $scope.location);
}
}
function Droid($scope) {
$scope.location = "Owen Farm";
$scope.$on('recall', function(e, newLocation) {
$scope.location = newLocation;
});
}
//html
<div ng-controller="Sandcrawler">
<p>Sandcrawler Location: {{location}}</p>
<button ng-click="recall()">Recall Droids</button>
<div ng-controller="Droid">
<p>Droid Location: {{location}}</p>
</div>
</div>
兄弟之間的傳播
function Sandcrawler($scope) {
$scope.$on('requestDroidRecall', function(e) {
$scope.$broadcast('executeDroidRecall');
});
}
function Droid($scope) {
$scope.location = "Owen Farm";
$scope.recallAllDroids = function() {
$scope.$emit('requestDroidRecall');
}
$scope.$on('executeDroidRecall', function() {
$scope.location = "Sandcrawler"
});
}
// html
<div ng-controller="Sandcrawler">
<div ng-controller="Droid">
<h2>R2-D2</h2>
<p>Droid Location: {{location}}</p>
<button ng-click="recallAddDroids()">Recall All Droids</button>
</div>
<div ng-controller="Droid">
<h2>C-3PO</h2>
<p>Droid Location: {{status}}</p>
<button ng-click="recallAddDroids()">Recall All Droids</button>
</div>
</div>