angular 控件间的传值

基于原型继承

父类的更改会触发所有的子类,子类的修改只会自身

Location: {{location}}

Location: {{location}}

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 注册事件 并由 emit 触发

向上

Sandcrawler Location: {{location}}

Droid Location: {{location}}

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

Sandcrawler Location: {{location}}

Droid Location: {{location}}

兄弟之间的传播

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

R2-D2

Droid Location: {{location}}

C-3PO

Droid Location: {{status}}

你可能感兴趣的:(angular 控件间的传值)