angularJS中controller的通信

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div ng-app="bb">
    <div ng-controller="abx">
        <ul ng-repeat="names in name track by $index">
            <li ng-bind="names.names"></li>
        </ul>
        <button ng-click="sub()">减</button>
        <span ng-bind="remark"></span>   {{remark}}
        <hr>
        <div ng-controller="aby">
            <button ng-click="add()">加</button>
            <span ng-bind="remark"></span>   {{remark}}
        </div>
    </div>
    <hr>
    <hr>
    <div ng-view></div>
</div>
</body>
<script src="Angular.js"></script>
<script src="route.js"></script>
<script>
    var app= angular.module("bb",['ngRoute']);
    app.controller("abx",function($rootScope,$scope){
        $scope.name=[
            {names:"123"},
            {names:"456"},
            {names:"789"},
        ];
        $scope.remark=100;
        $scope.$on("adds",function(event,data){
            $scope.remark+=data;
        });
        $scope.$on("subs",function(event,data){
            $scope.remark-=data;
        });
        $scope.sub = function(){
            $scope.$broadcast("subs",10);//向下广播
        };
    });

    app.controller("aby",function ($rootScope,$scope){
        $scope.remark=100;
        $scope.add=function(){
            $scope.$emit("adds",10);//向上广播
        };
        $scope.$on("adds",function(event,data){
            $scope.remark+=data;
        });
        $scope.$on("subs",function(event,data){
            $scope.remark-=data;
        });
    });
    //路由
    app.config(function ($routeProvider) {
        $routeProvider.when("/index",{
            controller: 'otherOneCtrl',
            templateUrl: 'templete/otherOne.html',
            publicAccess: true
        }).when("/index2",{
            controller: 'otherTwoCtrl',
            templateUrl: 'templete/otherTwo.html',
            publicAccess: true
        }).otherwise({
            redirectTo: '/index'
        });
    });

    app.controller("otherOneCtrl",function ($scope){
        $scope.other="other1";
    });
    app.controller("otherTwoCtrl",function ($scope){
        $scope.other="other2";
    });
</script>
</html>

  

posted @ 2015-05-01 08:58  soft.push("zzq")  Views(227)  Comments(0Edit  收藏  举报