Controller之间传值方法
- 通过value、constant、$rootscope等全局变量传值,只读
- 通过provider传值,可读可写。应用可参考我之前写的文章provider实现全局变量赋值
- 通过angularJS的消息时间,利用 on、 emit、$broadcast进行传值
说明
关于 on、 emit、$broadcast方法传值,有一点需要提前注明:
那就是,这种方法是基于angularJS提供的冒泡和隧道机制,因此只能从子控制器传到父控制器(使用$emit),或者从父控制器传到子控制器(使用$broadcast),不能进行平级controller之间的值传递。
代码结构
html代码
<!DOCTYPE html>
<html ng-app="demoForNotify">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script src="./lib/angular.js"></script>
<script src="./js/app.js"></script>
<script src="./js/controller.js"></script>
</head>
<body>
<div ng-controller="parentCtr">
<div ng-controller="childCtr1"> child 1 name :
<input ng-model="name" type="text" ng-change="change(name);"/>
</div>
<div ng-controller="childCtr2">child 2 name:
<input ng-model="child2Name"/>
</div>
</div>
<div ng-controller="parentBrotherCtr">
<div ng-controller="brotherChildCtr1">brotherChild 1 name :
<input ng-model="name" type="text" ng-change="change(name);"/>
</div>
<div ng-controller="brotherChildCtr2">brotherChild 2 name:
<input ng-model="brotherName2"/>
</div>
</div>
</body>
</html>
app.js
var demoForDirective = angular.module('demoForNotify', ['demoForNotify.controller']);
controller.js
/**
* Created by jywl on 2016/7/7.
*/
angular.module('demoForNotify.controller', [])
.controller("parentCtr",
function ($scope) {
$scope.$on("Ctr1NameChange",
function (event, msg) {
console.log("parent msg", msg);
$scope.$broadcast("Ctr1NameChangeFromParrent", msg);
});
})
.controller("childCtr1", function ($scope) {
$scope.change = function (name) {
console.log("childCtr1", name);
$scope.$emit("Ctr1NameChange", name);
};
})
.controller("childCtr2", function ($scope) {
$scope.$on("Ctr1NameChangeFromParrent",
function (event, msg) {
console.log("childCtr2", msg);
$scope.child2Name = msg;
});
})
.controller("parentBrotherCtr",
function ($scope) {
$scope.$on("Ctr1NameChange",
function (event, msg) {
console.log("parent msg", msg);
$scope.$broadcast("Ctr1NameChangeFromParrent", msg);
});
})
.controller("brotherChildCtr1", function ($scope) {
$scope.change = function (name) {
console.log("childCtr1", name);
$scope.$emit("Ctr1NameChange", name);
};
})
.controller("brotherChildCtr2", function ($scope) {
$scope.$on("Ctr1NameChangeFromParrent",
function (event, msg) {
console.log("childCtr2", msg);
$scope.brotherName2 = msg;
});
})
备注
其中app.js中仅有一句话,意思就是声明一个根作用域,然后包含了其他子作用域,其类型可以是service,controller,以及其他类型。这样写,更符合angularJS模块划分原则。同样也能够更好的利用angularJS提供的测试模块进行单元测试和集成测试。
所有原创文章,均首发CSDN-柠檬加冰博客