scope:{} 和 scope:true 内部指令有什么区别? [英] What is the difference between scope:{} and scope:true inside directive?

查看:50
本文介绍了scope:{} 和 scope:true 内部指令有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到有关 Angular.js 的信息,我在工作时注意到这两个值的工作方式不同.有什么区别?

.directive('foo', function() {返回 {范围:真实};});.directive('foo', function() {返回 {范围: {}};});

解决方案

scope: truescope:{} 都会为指令创建一个子作用域.但是,

scope:true 将原型继承自父级(例如指令所在的控制器)的属性,而 scope:{} 不会继承自父级的属性父,因此称为 isolated

例如,假设我们有一个控制器 c1 和两个指令 d1 和 d2,

app.controller('c1', function($scope){$scope.prop = "某个值";});.directive('d1', function() {返回 {范围:真实};});.directive('d2', function() {返回 {范围: {}};});<div ng-controller="c1"><d1><d1><d2><d2>

d1(scope:true) 将可以访问 c1 scope -> prop,因为 d2 与 c1 作用域隔离.

注意 1: d1 和 d2 都会为每个定义的指令创建一个新的作用域.

注意 2: 除了两者之间的区别之外,对于 scope:true - 对新子作用域所做的任何更改都不会反映回父作用域.但是,由于新作用域继承自父作用域,因此在 c1 作用域(父作用域)中所做的任何更改都将反映在指令作用域中.

提示:scope:{}isolated scope 用于可重用的 angular 指令.这样您就不会最终弄乱父作用域属性

I can't find this information about Angular.js and I notice while I was working that those two values work differently. What's the difference?

.directive('foo', function() {

  return {
    scope: true
  };
});

.directive('foo', function() {

  return {
    scope: {}
  };
});

解决方案

Both scope: true and scope:{} will create a child scope for the directive. But,

scope:true will prototypically inherit the properties from the parent(say the controller where the directive comes under) where as scope:{} will not inherit the properties from the parent and hence called isolated

For instance lets say we have a controller c1 and two directives d1 and d2,

app.controller('c1', function($scope){
  $scope.prop = "some value";
});

.directive('d1', function() {
  return {
    scope: true
  };
});

.directive('d2', function() {
  return {
    scope: {}
  };
});

<div ng-controller="c1">
  <d1><d1>
  <d2><d2>
</div>

d1(scope:true) will have access to c1 scope -> prop where as d2 is isolated from the c1 scope.

Note 1: Both d1 and d2 will create a new scope for each directive defined.

Note 2: Apart from the difference between the two, for scope:true - Any changes made to the new child scope will not reflect back to the parent scope. However, since the new scope is inherited from the parent scope, any changes made in the c1 scope(the parent scope) will be reflected in the directive scope.

Tip: Use scope:{} or isolated scope for reusable angular directives. So that you won't end up messing with the parent scope properties

这篇关于scope:{} 和 scope:true 内部指令有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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