Note
  • Introduction
  • JS
    • JS / JQuery 代码、框架收藏
    • 用Mock.js + AngularJS来提高开发效率
    • 在JavaScript中监听 IME 键盘输入事件
    • 如何组织大型JavaScript应用中的代码?
    • 深入理解javascript原型和闭包
      • 1. 一切都是对象
      • 2. 函数和对象的关系
      • 3. prototype原型
      • 4. 隐式原型
      • 5. instanceof
      • 6. 继承
      • 7. 原型的灵活性
      • 8. 简述【执行上下文】上
      • 9. 简述【执行上下文】下
      • 10. this
      • 11. 执行上下文栈
      • 12. 简介【作用域】
      • 13. 【作用域】和【上下文环境】
      • 14. 从【自由变量】到【作用域链】
      • 15. 闭包
      • 16. 补充:上下文环境和作用域的关系
    • AngularJS
      • AngularJS开发一些经验总结
      • AngularJS Controller 间通信机制
      • AngularJS 中的一些坑
      • 如何解决AngularJs在IE下取数据总是缓存的问题
      • AngularJS之$timeout指令
      • angular 代码日记
      • AngularJS Directive 隔离 Scope 数据交互
      • 在Angular指令中使用NgModelController做数据绑定
      • AngularJS的ngTransclude
      • 使用Angularjs的ng-cloak指令避免页面乱码
      • Directive - Compile vs. Link
    • NodeJS
      • npm的配置管理及设置代理
    • Angular
      • Angular2 - Control Validation on blur
      • Angular2 - how to call component function from outside the app
  • Go
    • How to Test Local Changes with Go Mod
  • Java
    • Java中根据字体得到字符串高度和长度
    • JAVA 判断一个字符串是不是一个合法的日期格式
    • JVM上的随机数与熵池策略
    • tomcat7+jdk的keytool生成证书 配置https
    • Spring
      • SpringMVC中用@ParamVariable传递的参数包含斜杠(/)时,匹配不了报404错误的解决方案
      • SpringMVC 中HttpMessageConverter简介和Http请求415 Unsupported Media Type的问题
      • Spring Boot 打包,分离依赖jar,配置文件
      • SpringBoot启动后 Stopping service [Tomcat]
      • spring-boot打包时排除第三方依赖
    • 第一个Eclipse插件
    • Eclipse 使用技巧
    • HighChart利用servlet导出中文PNG图片乱码问题解决
    • JDK中文字体在Linux操作系统的设置方案
    • Shiro
      • Shiro-Authentication(身份验证)
      • Shiro-Authorization(授权)
    • 详谈再论JAVA获取本机IP地址
  • Python
    • pip国内镜像源的配置
  • Linux
    • Shell脚本 bad interpreter:No such file or directory & /bin/bash^M: bad interpreter错误解决方法
    • 10个重要的Linux ps命令实战
    • Linux 下执行定时任务 crontab 命令详解
    • CentOS 7.x设置自定义开机启动,添加自定义系统服务
    • CentOS 7 下使用 Firewall
    • 在Ubuntu 12.04安装和设置SSH服务
    • 配置CENTOS YUM更新源
    • Linux下终端利器tmux
    • scp命令
    • Linux系统管理常用命令
    • 让你提升命令行效率的 Bash 快捷键 [完整版]
    • SELinux
    • Linux下 RabbitMQ的安装与配置
    • SELinux下更改mysql端口
    • centos 7 升级后yum install出现Exiting on user cancel
    • Linux Shell 通配符、元字符、转义符使用实例介绍
  • Other
    • Docker
      • Docker Proxy
    • Swagger
      • Spring MVC 集成 Swagger
    • Maven
      • maven plugin的execution出错
      • nexus repair或update index 没反应 速度慢 手动配置nexus index
      • nexus 搭建 maven 私服
      • Maven类包冲突终极解决小技若干
      • org.codehaus.plexus.archiver.jar.Manifest.merge(org.codehaus.plexus.archiver.jar.Manifest)
      • Maven 生命周期
      • wagon-maven-plugin
      • Maven中-DskipTests和-Dmaven.test.skip=true的区别
    • MySQL
      • is not allowed to connect to this MySQL server 解决办法
      • MySQL备份--mysql dump
      • MySQL启动中 InnoDB: Error: log file ./ib_logfile0 is of different size 0 5242880 bytes 的问题
      • MySQL修改root密码的多种方法
      • MySQL长事务导致的Table Metadata Lock
      • com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
      • 解决mysql插入数据时出现Incorrect string value: '\xF0\x9F...' for column 'name' at row 1的异常
    • HTTP
      • HTTP 协议中的 Transfer-Encoding
      • 四种常见的 POST 提交数据方式
      • HTTP 请求头中的 X-Forwarded-For
      • 传统轮询、长轮询、服务器发送事件与WebSocket
    • Raspberry
      • 系统安装配置
    • VIM
      • vim常用配置
      • 在vim中使用查找命令查找指定字符串
      • Vim缩进有关的设置总结
    • Git
      • github 同步一个 fork
      • Git 如何 clone 非 master 分支的代码
      • git提示error setting certificate verify locations解决办法
      • git设置和取消代理
      • How to Delete Commit History in Github
      • Windows下使用Beyond Compare作为git的比对与合并工具
    • 解决 Virtualbox 共享文件夹 cannot create symlink error 问题
    • nginx 403 forbidden 二种原因
    • VirtualBox的四种网络连接方式
    • 在Windows的CMD中如何设置支持UTF8编码?
    • nginx使用ssl模块配置HTTPS支持
    • 怎么查看WINDOWS端口被哪个程序占用
    • VMWare 随系统启动指定虚拟机
    • 使用命令行启动VirtualBox虚拟机
    • 该死的^M
    • install home-assistant mosquitto-broker and node-red on android
    • SSH原理与运用:远程登录、远程操作与端口转发
    • SVN mime-type 笔记
    • VirtualBox虚拟机网络配置(NAT + Host-only - Bridged)
    • VirtualBox绿色版的桥接网卡驱动安装
    • OAuth的改变
    • MavenActionUtil.getMavenProject(e.getDataContext()) is Null when developing a intellij plugin
    • Cygwin的安装和配置apt-cyg源
    • Zookeeper运维常用四字命令
    • svn sqlite[S11]: database disk image is malformed
Powered by GitBook
On this page
  • 什么是隔离 Scope
  • 为什么使用隔离 Scope
  • 如何在 directive 中创建隔离 scope
  • 隔离 scope 和父 scope 如何交互
  • 使用小结

Was this helpful?

  1. JS
  2. AngularJS

AngularJS Directive 隔离 Scope 数据交互

什么是隔离 Scope

AngularJS 的 directive 默认能共享父 scope 中定义的属性,例如在模版中直接使用父 scope 中的对象和属性。通常使用这种直接共享的方式可以实现一些简单的 directive 功能。当你需要创建一个可重复使用的 directive,只是偶尔需要访问或者修改父 scope 的数据,就需要使用隔离 scope。当使用隔离 scope 的时候,directive 会创建一个没有依赖父 scope 的 scope,并提供一些访问父 scope 的方式。

为什么使用隔离 Scope

当你想要写一个可重复使用的 directive,不能再依赖父 scope,这时候就需要使用隔离 scope 代替。共享 scope 可以直接共享父 scope,而隔离 scope 无法共享父scope。下图解释共享 scope 和隔离 scope 的区别: 示例:

共享 scope 使用共享 scope 的时候,可以直接从父 scope 中共享属性。因此下面示例可以将那么属性的值输出出来。使用的是父 scope 中定义的值。

app.controller("myController", function ($scope) {
    $scope.name = "hello world";
    }).directive("shareDirective", function () {
    return {
            template: 'Say:{{name}}'
    }
});
<div ng-controller="myController">
  <div share-directive=""></div>
</div>

输出结果:

Say:hello world

隔离 scope 使用隔离 scope 的时候,无法从父 scope 中共享属性。因此下面示例无法输出父 scope 中定义的 name 属性值。

app.controller("myController", function ($scope) {
    $scope.name = "hello world";
}).directive("isolatedDirective", function () {
        return {
            scope: {},
            template: 'Say:{{name}}'
        }
});
<div ng-controller="myController">
  <div isolated-directive=""></div>
</div>

输出结果:

Say:

从上图可以看出共享 scope 允许从父 scope 渗入到 directive 中,而隔离 scope 不能,在隔离 scope 下,给 directive 创造了一堵墙,使得父 scope 无法渗入到 directive 中。

如何在 directive 中创建隔离 scope

在 directive 中创建隔离 scope 很简单,只需要定义一个 scope 属性即可,这样,这个 directive 的 scope 将会创建一个新的 scope,如果多个 directive 定义在同一个元素上,只会创建一个新的 scope。

angular.module('app').controller("myController", function ($scope) {
    $scope.user = {
            id:1,
            name:"hello world"
    };
}).directive('isolatedScope', function () {
    return {
        scope: {},
        template: 'Name: {{user.name}} Street: {{user.addr}}'
    };
});

现在 scope 是隔离的,user 对象将无法从父 scope 中访问,因此,在 directive 渲染的时候 user 对象的占位将不会输出内容。

隔离 scope 和父 scope 如何交互

directive 在使用隔离 scope 的时候,提供了三种方法同隔离之外的地方交互。这三种分别是 @ 绑定一个局部 scope 属性到当前 dom 节点的属性值。结果总是一个字符串,因为 dom 属性是字符串。 & 提供一种方式执行一个表达式在父 scope 的上下文中。如果没有指定 attr 名称,则属性名称为相同的本地名称。 = 通过 directive 的 attr 属性的值在局部 scope 的属性和父 scope 属性名之间建立双向绑定。

@ 局部 scope 属性 @ 方式局部属性用来访问 directive 外部环境定义的字符串值,主要是通过 directive 所在的标签属性绑定外部字符串值。这种绑定是单向的,即父 scope 的绑定变化,directive 中的 scope 的属性会同步变化,而隔离 scope 中的绑定变化,父 scope 是不知道的。

如下示例:directive 声明未隔离 scope 类型,并且使用@绑定 name 属性,在 directive 中使用 name 属性绑定父 scope 中的属性。当改变父 scope 中属性的值的时候,directive 会同步更新值,当改变 directive 的 scope 的属性值时,父 scope 无法同步更新值。

app.controller("myController", function ($scope) {
        $scope.name = "hello world";
    }).directive("isolatedDirective", function () {
        return {
            scope: {
                name: "@"
            },
            template: 'Say:{{name}} <br>改变隔离scope的name:<input type="buttom" value="" ng-model="name" class="ng-pristine ng-valid">'
        }
})
<div ng-controller="myController">
   <div class="result">
        <div>父scope:
            <div>Say:{{name}}<br>改变父scope的name:<input type="text" value="" ng-model="name"/></div>
        </div>
        <div>隔离scope:
            <div isolated-directive name="{{name}}"></div>
        </div>
        <div>隔离scope(不使用{{name}}):
            <div isolated-directive name="name"></div>
        </div>
    </div>
</div>

= 局部 scope 属性 = 通过 directive 的 attr 属性的值在局部 scope 的属性和父 scope 属性名之间建立双向绑定。 意思是,当你想要一个双向绑定的属性的时候,你可以使用=来引入外部属性。无论是改变父 scope 还是隔离 scope 里的属性,父 scope 和隔离 scope 都会同时更新属性值,因为它们是双向绑定的关系。

示例代码:

app.controller("myController", function ($scope) {
    $scope.user = {
        name: 'hello',
        id: 1
    };
}).directive("isolatedDirective", function () {
    return {
        scope: {
            user: "="
        },
        template: 'Say:{{user.name}} <br>改变隔离scope的name:<input type="buttom" value="" ng-model="user.name"/>'
    }
})
<div ng-controller="myController">
    <div>父scope:
        <div>Say:{{user.name}}<br>改变父scope的name:<input type="text" value="" ng-model="user.name"/></div>
    </div>
    <div>隔离scope:
        <div isolated-directive user="user"></div>
    </div>
    <div>隔离scope(使用{{name}}):
        <div isolated-directive user="{{user}}"></div>
    </div>
</div>

& 局部 scope 属性 & 方式提供一种途经是 directive 能在父 scope 的上下文中执行一个表达式。此表达式可以是一个 function。 比如当你写了一个 directive,当用户点击按钮时,directive 想要通知 controller,controller 无法知道 directive 中发生了什么,也许你可以通过使用 angular 中的 event 广播来做到,但是必须要在 controller 中增加一个事件监听方法。 最好的方法就是让 directive 可以通过一个父 scope 中的 function,当 directive 中有什么动作需要更新到父 scope 中的时候,可以在父 scope 上下文中执行一段代码或者一个函数。

如下示例在 directive 中执行父 scope 的 function。

app.controller("myController", function ($scope) {
    $scope.value = "hello world";
    $scope.click = function () {
        $scope.value = Math.random();
    };
}).directive("isolatedDirective", function () {
    return {
        scope: {
            action: "&"
        },
        template: '<input type="button" value="在directive中执行父scope定义的方法" ng-click="action()"/>'
    }
})
<div  ng-controller="myController">
        <div>父scope:
            <div>Say:{{value}}</div>
        </div>
        <div>隔离scope:
            <div isolated-directive action="click()"></div>
        </div>
</div>

使用小结

Previousangular 代码日记Next在Angular指令中使用NgModelController做数据绑定

Last updated 5 years ago

Was this helpful?

示例请点击:

具体文档可以参考:

具体演示请看:

具体演示请看:

具体演示请看:

在了解 directive 的隔离 scope 跟外部环境交互的三种方式之后,写一些通用性的组件更加便捷和顺手。不再担心在 directive 中改变外部环境中的值,或者执行函数的重重困境了。 更多请参考API文档: 。 如有纰漏,请指正!

转自:

http://kin-sample.coding.io/angular/directive/share-and-isolated-scope.html
https://docs.angularjs.org/guide/directive#isolating-the-scope-of-a-directive
http://kin-sample.coding.io/angular/directive/isolated-scope-at-interact.html
http://kin-sample.coding.io/angular/directive/isolated-scope-eq-interact.html
http://kin-sample.coding.io/angular/directive/isolated-scope-ad-interact.html
https://docs.angularjs.org/api/ng/service/$compile
https://blog.coding.net/blog/angularjs-directive-isolate-scope