javascript - AngularJS 指令隔离范围

标签 javascript angularjs

我正在学习 AngularJS 中的指令,并且遇到了这段代码:

var app = angular.module('app', []);
//creating custom directive syntax
app.directive("myDir", function () {
return {
        restrict: "E", //define directive type like E = element, A = attribute, C =
        class, M = comment
        scope: { //create a new child scope or an isolate scope
     title: '@' //@ reads the attribute value,
 //= provides two-way bindi

我的问题是:

根据代码,属性“scope”显然用于创建子范围或隔离范围。那么我们如何区分是否希望该指令的范围被隔离?如果我只想有一个范围子级而不是隔离我该怎么办?

隔离意味着我们创建的隔离作用域无法访问父作用域中的变量,对吗?

默认情况下,父作用域无法访问子作用域的变量,但是如果父作用域未隔离,则子作用域可以访问父作用域的变量,对吗?

最后一个问题,如果我们定义一个属性“controller”来指定该指令的 Controller ,那么该指令将默认具有 Controller 的范围?

谢谢!!

最佳答案

设置 scope: true 以获取未隔离的新子作用域。

来自angular-js docs :

scope

If set to true, then a new scope will be created for this directive. If multiple directives on the same element request a new scope, only one new scope is created. The new scope rule does not apply for the root of the template since the root of the template always gets a new scope.

If set to {} (object hash), then a new "isolate" scope is created. The 'isolate' scope differs from normal scope in that it does not prototypically inherit from the parent scope. This is useful when creating reusable components, which should not accidentally read or modify data in the parent scope.

关于javascript - AngularJS 指令隔离范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29498537/

相关文章:

javascript - 如何在 Angular.js 中从 html 传输数据?

javascript - .toggleClass 不切换某个类,但正在处理所有其他类

c# - 有没有办法将功能与用户控件关联起来

javascript - Jest - 调用模拟函数不计算在内

javascript - 将数据从 Python 返回到 Javascript

javascript - 使用 ng-repeat 或 ng-options 选择框 Angular 并删除空白选项

javascript - AngularJS 将两个列表合二为一

javascript - 拒绝从 '*' 执行脚本

css - 从可拖动的 angular-dnd-list div 复制文本

javascript - 想要 Javascript 无限循环运行