angularJs controller間怎麼通訊

做用域能夠像DOM節點同樣,進行事件的傳播。主要是有兩個方法:html

broadcasted :從父級做用域廣播至子級 scopeapp

emitted :從子級做用域往上發射到父級做用域code

下面是代碼案例htm

<div class="container" ng-controller="parentCtrl">

    <div class="row" ng-controller="childCtrl">
        <input type="text" ng-model="cv" ng-change="change(cv)">
    </div>
    <div class="row" ng-controller="childCtrl2">
        {{ cv2 }}
    </div>

</div>
'use strict';
angular.module('app', [])
    .controller('parentCtrl', ['$scope', function ($scope) {
        $scope.$on('childCtrlChange', function (event, msg) {
            $scope.$broadcast('childAll', msg);
        });
    }])
    .controller('childCtrl', ['$scope', function ($scope) {
        $scope.change = function (msg) {
            $scope.$emit('childCtrlChange', msg);
        };
    }])
    .controller('childCtrl2', ['$scope', function ($scope) {
        $scope.$on('childAll', function (event, msg) {
            $scope.cv2 = msg;
        });
    }]);
相關文章
相關標籤/搜索