zoukankan      html  css  js  c++  java
  • 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 值,就可以调用相应组件中的方法啦。

  • 相关阅读:
    【搜索引擎】Solr最新安装以及通过关系型数据库(MySQL,Oracle,PostgreSQL)导入数据
    【搜索引擎】SOLR VS Elasticsearch(2019技术选型参考)
    【Java源码】集合类-优先队列PriorityQueue
    【Java源码】树-概述
    Go语言调度器之创建main goroutine(13)
    Go语言goroutine调度器初始化(12)
    Go语言goroutine调度器概述(11)
    线程本地存储及实现原理
    操作系统线程及线程调度
    系统调用
  • 原文地址:https://www.cnblogs.com/guofan/p/8360211.html
Copyright © 2011-2022 走看看