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 值,就可以调用相应组件中的方法啦。
标签:
angular
, angular1.5组件学习
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现