AngularJs框架下controller间的传值方法

AngularJs框架下controller间的传值方法



第一种方式
angularJS中默认情况下,当前作用域中无法找到某个属性时,就会在父级作用域中进行查找,若找不到直至查找到$rootScope。
如果在$rootScope中也无法找到程序依旧运行,但视图不会更新。

//Javascript
app.controller('ParentController', function($scope) {
$scope.person = {greeted: false};
});
app.controller('ChildController', function($scope) {
$scope.sayHello = function() {
$scope.person.name = 'Ari Lerner';
};
});
//HTML
<div ng-controller="ParentController">
<div ng-controller="ChildController">
<a ng-click="sayHello()">Say hello</a>
</div>
{{ person }}
</div>
//result
{"greeted":false, "name": "Ari Lerner"}




第二种方式
$on、$emit和$broadcast使得event、data在controller之间的传递变的简单
$emit只能向parent controller传递event与data
$broadcast只能向child controller传递event与data
$on用于接收event与data //

JavaScript
app.controller('ParentController', function($scope) {
$scope.$on('$fromSubControllerClick', function(e,data){
console.log(data); // hello
});
});
app.controller('ChildController', function($scope) {
$scope.sayHello = function() {
$scope.$emit('$fromSubControllerClick','hello');
};
});
//HTML
<div ng-controller="ParentController">
<div ng-controller="ChildController">
<a ng-click="sayHello()">Say hello</a>
</div>
</div>




第三种方式
利用angularJS中service单例模式的特性,服务(service)提供了一种能在应用的整个生命周期内保持数据的方式,
能够在控制器之间进行通信,且能保证数据的一致性。

JavaScript
var myApp = angular.module("myApp", []);
myApp.factory('Data', function() {
return {
name: "Ting"
}
});
myApp.controller('FirstCtrl', function($scope, Data) {
$scope.data = Data;
$scope.setName = function() {
Data.name = "Jack";
}
});
myApp.controller('SecondCtrl', function($scope, Data) {
$scope.data = Data;
$scope.setName = function() {
Data.name = "Moby";
}
});

猜你喜欢

转载自huangyongxing310.iteye.com/blog/2324178