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;
        });
    }]);
相关文章
相关标签/搜索