angular1.5 组件学习 -- 4.1、组件的其他属性 require

那 component 除了 template、controller、bindings,是否还有别的属性呢?答案是肯定的!

require 属性,值为一个对象。用于复用其他组件的控制器。

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

<body>
    <grandparent-component></grandparent-component>
    <script>
        angular.module('myApp',[])
            .component('grandparentComponent', {
                template: "grandparentComponent > <parent-component></parent-component>",
                controller: function () {
                    this.loadDone = function (value) {
                        return value;
                    }
                    this.$onInit = function () {
                        console.log('Grandparent Loaded !');
                    }
                }
            })
            .component('parentComponent', {
                template: "parentComponent > <child-component></child-component>",
                require: {
                    parent: '^grandparentComponent',
                },
                controller: function () {
                    this.loadDone = function (value) {
                        return this.parent.loadDone(value);
                    }
                    this.$onInit = function () {
                        console.log('Parent Loaded !');
                    }
                }
            })
            .component('childComponent', {
                template: "<span>childComponent : {{$ctrl.status}}</span>",
                require: {
                    parent: '^parentComponent',
                    grandparent: '^grandparentComponent',
                },
                controller: function () {
                    this.status = 'Not Loaded';
                    this.$onInit = function () {
                        this.status = this.grandparent.loadDone('Loaded');
                        console.log("Child",this.parent.loadDone('Loaded !'));
                    }
                }
            })
    </script>
</body>
</html>

require 值前面是 ^ 那么首先会在当前组件搜寻是否有该控制器,如果没有再在其父组件中搜寻。

^^ 则直接在当前组件的父组件中搜寻相应控制器。 找到后就可以通过 this.parent.方法名 来调用父组件中的方法了。

这里需要注意:

  1、require 只能在组件链上,且只能向上找相应名称的控制器。

  2、定义的 require 对象中,key 值自定义,只要 controller 中引用定义的 key 值,就可以调用相应组件中的方法啦。

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