首页 > 其他 > 详细

angular的继承作用域通信

时间:2017-03-30 19:29:46      阅读:210      评论:0      收藏:0      [点我收藏+]

本人学了一段时间的angular,angular之间怎样通信,我就总结以下几点,如果有哪位大神认为不对,敬请赐教。

1、父子之间的作用域进行通信

html

<div ng-controller="Parent">

  {{name}}                                //Parent
  <div ng-controller="child">
    {{name}}                          //Parent
  </div>
</div>

js

m1.controller("Parent",["$scope",function($scope){

  $scope.name = "Parent";
}])
m1.controller("child",["$scope",function($scope){

}])

2、$rootScope 挂在全局作用域上,适用范围更广

html

<div ng-controller="myCtrl">

  {{name}}                                  //Parent
  <div ng-controller="Parent">
    {{name}}                            //Parent
    <div ng-controller="child">
      {{name}}                      //Parent
    </div>
  </div>

</div>

js

m1.controller("Parent",["$scope","$rootScope",function($scope,$rootScope){
  $scope.name = "Parent";
  $rootScope.name = $scope.name;
}])
m1.controller("child",["$scope",function($scope){
}])

 3、基于事件的数据传递  组件 webcomponent

html

 

<div ng-controller="Parent">

  <input type="text" ng-model="name" ng-change="change()">  
  <div ng-controller="child">
    <input type="text" ng-model="name" ng-change="change()">   
  </div>
  <div ng-controller="secChild">
    <input type="text" ng-model="name">
  </div>
</div>

js

m1.controller("Parent",["$scope","$rootScope",function($scope,$rootScope){

  // 监听 发送消息  $emit
  $scope.$on("changeName",function(event,data){
    console.log(data);
    //$broadcast 广播 广播只有子级和自己知道,父级(就是Parent更上级)不知道
    $scope.$broadcast("sendName",data);
  })

  //监听 $broadcast 广播发送的消息 

  $scope.$on("sendName",function(event,data){
    console.log(data);
    $scope.name = data;
   })
}])
m1.controller("child",["$scope",function($scope){
  $scope.name = "第一个孩子";
  $scope.change = function(){
    //$emit 发送 只能发送自己的父级
    $scope.$emit("changeName","发送-》广播");
  }

  //监听 $broadcast 广播发送的消息
   $scope.$on("sendName",function(event,data){
    console.log(data);
    $scope.name = data;
   })
}])
m1.controller("secChild",["$scope",function($scope){
  $scope.name = "第二个孩子";

  //监听 $broadcast 广播发送的消息
  $scope.$on("sendName",function(event,data){
    console.log(data);
    $scope.name = data;
  })
}])

总结:

 

angular的继承作用域通信

原文:http://www.cnblogs.com/shirly77/p/6647257.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!