angular.js控制器之间的通信

环境:angular.js+sastruts+apache-tomcat

学习前端的一个设计工具angular.js的过程中会遇到这样一个问题:angular.js控制器之间的通信。

查看了一些资料,大体有以下的解决方案。

1.使用$on,$emit,$boardcast这几个方式来实现,其中$on表示事件监听,$emit表示向父级以上的作用域触发事件,$boardcast表示向子级以下的作用域广播事件。即子控制器中的变量通过$emit向父级控制器传播,父级控制器中通过$on事件监听,并使用$boardcast将事件向子级控制器传播。这样子级控制器就可以得到其他控制器中的变量了。

controller.js

function parendCtrl($scope) {
    $scope.$on('requestRecall', function(e, location) {
        $scope.$broadcast('executeRecall', location);
    });
}

function child1Ctrl($scope) {
    $scope.location = "child1Ctrl";
    $scope.recall = function(location) {
        $scope.$emit('requestRecall', location);
    }
}

function child2Ctrl($scope) {
    $scope.location = "child2Ctrl";
    $scope.$on('executeRecall', function(e, location) { 
        $scope.location = location;
    });
}
html
<div ng-controller="parendCtrl">
    <div ng-controller="child1Ctrl">
        <p>Location: {{location}}</p>
        <button ng-click="recall(location)">Recall</button>
    </div>
    <div ng-controller="child2Ctrl">
        <p>Location: {{location}}</p>
    </div>
</div>
2.使用根作用域$rootScope来实现,即将子,父控制器中的变量放到$rootScope中,来实现数据共享。

controller.js

function parendCtrl($scope) {
    ...
}

function child1Ctrl($scope, $rootScope) {
    $scope.location = "child1Ctrl";
    $scope.recall = function(location) {
    	$rootScope.rootLocation = location;
    }
}

function child2Ctrl($rootScope) {
    $rootScope.rootLocation = "child2Ctrl";
}
html
<div ng-controller="parendCtrl">
    <div ng-controller="child1Ctrl">
        <p>Location: {{location}}</p>
        <button ng-click="recall(location)">Recall</button>
    </div>
    <div ng-controller="child2Ctrl">
        <p>Location: {{rootLocation}}</p>
    </div>
</div>
3.angular服务的方式,可参看 参考资料中的描述。

参考资料:http://www.html-js.com/article/1560

感谢热心的前辈!!本文如有不正,请指出。

以上。

你可能感兴趣的:(通信,控制器,angular.js)