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

一个组件干一个事,一个完整的功能有时需要多个组件协调完成,这就少不了组件间的数据交互,那先来记录下父组件向子组件传递数据。

<!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 <input ng-model='$ctrl.sayHello'></h3>" + 
                "<child-component say-some='$ctrl.sayHello'></child-component>",
                controller: function () {
                    this.sayHello = 'Hello';
                }
            })
            .component('childComponent', {
                template: "<h3>child-component <input ng-model='$ctrl.saySome'></h3>",
                controller: function () {
                    this.$onChanges = function (event) {
                        console.log(event);
                    }
                },
                bindings: {
                    saySome: "<"
                }
            })
    </script>
</body>
</html>

类似于调用指令时与指令的数据传递:将要绑定的变量写在调用的子组件自定义元素标签上,然后子组件通过 bindings 属性设置绑定的变量名(此名称为子组件作用域内供调用的变量名称)。

绑定的属性有三种前缀标识符可设置:

  1、“@”,单项绑定的前缀标识符,用于传递字符串;

  2、“=”,双向绑定标识符,父组件与子组件的变量的变化会相互影响;

  此基础上 compnent 还增加了一种标识符:

  3、“<”,单项数据传输,父组件状态的改变会传给子组件,子组件状态改变不会影响父组件状态。组件中建议使用此标识符,可触发生命周期钩子:$onChanges(changesObj)。

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