为什么指令有作用域? [英] Why directive has scope?

查看:35
本文介绍了为什么指令有作用域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,基本上 scope 是控制器的一个实例.

As far as I know that basically scope is an instance of a controller.

每次我声明一个控制器时,scope 将可用于该控制器.

Every time I declare a controller scope will be available for that controller.

但是为什么指令在链接函数中有scope?

But then why directive has scope in link function ?

我没有为指令声明任何控制器.

I didn't declare any controller for the directive.

那为什么 link 函数有 scope 呢?有什么想法吗?

Then why link function has scope ? Any Idea ?

推荐答案

来自 文档:

范围:指令用于注册 手表.

scope: The scope to be used by the directive for registering watches.

您可能也有兴趣查看 $scope 和 scope.

You may also be interested to see the differences between $scope and scope.

所有指令都有一个与它们相关联的作用域.他们使用这个范围来访问模板和链接函数中的数据/方法.默认情况下,除非明确设置,否则指令不会创建自己的作用域.因此,指令使用其父作用域(通常是控制器)作为自己的作用域.

All directives have a scope associated with them. They use this scope for accessing data/methods inside the template and link function. By default, unless explicitly set, directives don’t create their own scope. Therefore, directives use their parent scope ( usually a controller ) as their own.

然而,AngularJS 允许我们通过传递一个称为指令定义对象的配置对象来更改指令的默认范围.指令定义对象——我们称之为 DDO——是一个简单的 JavaScript 对象,用于配置指令的行为、模板等.查看 AngularJS docs 关于 DDO.

However, AngularJS allows us to change the default scope of directives by passing a configuration object known as directive definition object. A directive definition object –– let’s call it as DDO –– is a simple JavaScript object used for configuring the directive’s behaviour,template..etc. Check out AngularJS docs about DDO.

因此,我们可以在链接函数内使用作用域来处理父作用域、子作用域或隔离作用域.

So, we can use scope inside linking function to work with parent scope, child scope or isolated scope.

您可以访问 this 有关指令内作用域的详细信息.

You may visit this for detailed information about scope inside directive.

您可以分享控制器和链接函数之间的数据.

有时我们希望在 Angular 指令中的控制器和链接函数中访问相同的数据.通常我们将这些数据添加到范围对象中.这有一些问题,例如将其暴露给任何子作用域.将共享属性添加到控制器实例本身并在链接函数中访问.

Sometimes we would like to access that same data in both controller and link functions in Angular directive. Usually we add this data to the scope object. This has certain problems, for example exposing it to any child scope. Add the shared properties to the controller instance itself and access in the link function.

您可能还对 需要什么链接功能?

这篇关于为什么指令有作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆