是什么范围之间的区别:与范围{}:内部指令真的吗? [英] What is the difference between scope:{} and scope:true inside directive?

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

问题描述

我找不到有关Angular.js此信息,并通知我,而我工作的这两个值的工作方式不同。有什么区别?

  .directive('富',函数(){  返回{
    适用范围:真
  };
});.directive('富',函数(){  返回{
    范围: {}
  };
});


解决方案

两个范围:真正的范围:{} 将创建指令子作用域。但是,

范围:真正的将中典型继承父的属性(比如说控制器所在的指令来下),其中为范围:{} 不会继承父的特性,因此被称为隔离

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

  app.controller('C1',函数($范围){
  $ scope.prop =一些价值;
});.directive(D1,函数(){
  返回{
    适用范围:真
  };
});.directive(D2,函数(){
  返回{
    范围: {}
  };
});< D​​IV NG控制器=C1>
  < D​​1>< D​​1>
  < D​​2>< D​​2>
< / DIV>

D1(范围:TRUE)将有机会获得C1范围 - >道具,其中为d2是从C1范围隔离。

注1: D1和D2将为定义的每个指令一个新的作用域。

注意2:除了为范围两个之间的区别:真 - 到新的子范围所做的任何更改将不反映回父范围。然而,由于新的范围是从父作用域继承,在C1范围(父作用域)所作的任何更改将反映在该指令范围。

提示:使用范围:{} 隔离范围可重复使用的角度指令。这样你就不会结束与父作用域属性搞乱

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

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

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