angular1.5 组件学习 -- 2.2、组件间的交互:子向父

有父组件向子组件传递数据,那必然会有子组件向父组件返回数据。这时将使用事件绑定来调用父组件中的方法,告诉父组件:子组件有数据给你,接着。

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>子组件向父组件发送数据</title>
    <script src="angular.js"></script>
</head>

<body>
    <father-component></father-component>
    <script>
        angular.module('myApp',[])
            .component('fatherComponent', {
                template: "<h3>father-component {{$ctrl.sayHello}}</h3>" + 
                "<child-component say-some='$ctrl.sayHelloFnc(text)'></child-component>",
                controller: function () {
                    this.sayHelloFnc = function (value) {
                        this.sayHello = value;
                    };
                }
            })
            .component('childComponent', {
                template: "<h3>child-component " + 
                "<button ng-click='$ctrl.sendMessage();'>send message</button></h3>",
                controller: function () {
                    this.sendMessage = function () {
                        this.saySome({text: 'Hello'})
                    }
                },
                bindings: {saySome: "&"}
            })
    </script>
</body>
</html>

子向父传递时,绑定父组件的方法,同样是在子组件元素标签上绑定,然后子组件的 bindings 属性绑定相应在子组件中调用父组件的名称即可,这里使用前缀标识符: “&” 。

注意一点,参数传递是以 json 形式传递的,所以子组件使用创建对象将数据保存到一个属性的方式传递数据,并在父组件方法绑定处增加相应属性来解析。

原文地址:https://www.cnblogs.com/guofan/p/8360065.html