zoukankan      html  css  js  c++  java
  • Angular $broadcast和$emit和$ond实现父子通信

    <!DOCTYPE html>
    <html ng-app="myApp">
    <head lang="en">
    <meta charset="UTF-8">
    <script src="js/angular.js"></script>
    <title></title>
    </head>
    <body>

    <div ng-controller="parentCtrl">
    <button ng-click="toChild()">
    向child传值
    </button>

    <div ng-controller="childCtrl">
    <p>{{data}}</p>
    <button ng-click="toParent()">向parent传值</button>
    </div>

    </div>


    <script>
    var app = angular.module('myApp', ['ng']);

    app.controller('parentCtrl', function ($scope) {
    $scope.toChild = function () {
    //通过事件传值 约定事件名称:toChildEvent
    $scope.$broadcast(
    'toChildEvent',
    ' msg from parent')
    }

    //绑定toParentEvent事件的处理函数
    $scope.$on('toParentEvent',
    function (event, result) {
    console.log(result);
    })

    });

    app.controller('childCtrl', function ($scope) {
    //绑定事件 $on
    $scope.$on('toChildEvent',
    function (event, result) {
    console.log(arguments);
    $scope.data = result;
    });

    $scope.toParent = function () {
    //向父级元素通过事件传值 $emit 约定:toParentEvent
    $scope.$emit(
    'toParentEvent',
    'msg to my parent'
    );
    }

    });

    </script>
    </body>
    </html>
  • 相关阅读:
    std::function与std::bind 函数指针
    cocos2dx 3.0 +VS2013 环境搭建
    matrix(dp)
    sequence1(暴力)
    uva
    hpu第五届acm比赛
    找球号(一)(hask表)
    Elven Postman(二叉树)
    链表的基本操作
    Sightseeing Cows(最优比率环)
  • 原文地址:https://www.cnblogs.com/dianzan/p/7284246.html
Copyright © 2011-2022 走看看