我正在学习 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/