【问题标题】:Parent - child scope hierarchy when defining Angular directives定义 Angular 指令时的父子范围层次结构
【发布时间】:2016-10-25 12:12:57
【问题描述】:

我目前正在学习 AngularJS,并且正在阅读有关将变量从指令的父范围绑定到指令的隔离范围的方法。我对范围层次结构有一些理解问题。

有一个简单且有效的颜色选择器指令示例:

index.html

<!DOCTYPE html>
<html ng-app="colorPickerApp">
<head>
  <meta charset="utf-8">
  ...
</head>
<body>    
  <h1>AngularJS Colorpicker</h1>

  <color-picker init-r="255"
    init-g="0"
    init-b="123"
    init-a="0.7"
    on-change="onColorChange(r, g, b, a)">
  </color-picker>    
  <script type="text/javascript" src="colorPickerApp.js"></script>
</body>
</html>

colorPickerApp.js

var colorPickerApp = angular.module('colorPickerApp', []);

colorPickerApp.directive('colorPicker', function(){
  return {
    scope: {
      r: '@initR', // init-r <==> initR
      g: '@initG',
      b: '@initB',
      a: '@initA',
      onChange: '&'
    },
    restrict: 'E',
    templateUrl: './ColorPicker.html',
  };
});

ColorPicker.html

Red channel:<input type="range" min="0" max= "255" step="1" ng-model="r"><br>
Green channel:<input type="range" min="0" max="255" step="1" ng-model="g"><br>
Blue channel:<input type="range" min="0" max="255" step="1" ng-model="b"><br>
Alpha channel:<input type="range" min="0" max="1" step="0.01" ng-model="a">
<div style="width: 300px; height: 100px; background-color: rgba( {{r}}, {{g}}, {{b}}, {{a}});">
<div>

因此,显然,initR/G/B/A 来自指令的父范围。根据定义,范围是 " ...在特定上下文中定义的一组变量或函数。上下文是 DOM 的特定部分" 我的模板在具有这些属性的 index.html 中实例化。我不明白是什么让它们成为指令的父范围?

--- 编辑 --- 为了让我的困惑更清楚,我创建了以下图像:

  • 用于颜色选择器初始化的属性没有被声明为控制器的一部分。我可以在其他地方访问这些属性吗?
  • 我希望,颜色选择器范围 - 红色的将是指令的范围。但是该指令在其父范围内访问这些属性。所以,红色范围实际上是蓝色范围???

【问题讨论】:

  • 例如,您不能将 [scope.x] 从 [childController] 发送到 [parentController],因为 [scope.x] 没有在 [parentController] 中定义,在这种情况下,首先您有在控制器中定义 [scope.x],然后将其发送到指令进行更改,然后再次将其返回到控制器以获取范围结果。
  • 感谢您的回复,但本例中没有使用没有明确模型声明 ($scope.x) 的控制器。我刚刚在 AngularJS 书中找到了这个例子。

标签: javascript angularjs angularjs-directive angularjs-scope


【解决方案1】:

我想我找到了对我的问题的解释。指令的隔离范围的属性外部世界之间的链接,在scope:对象中使用@完成= & 运算符(前缀)在隔离范围和指令属性之间创建关系,该关系可以从父范围

进一步实例化

Angular Wiki 对这个话题说如下:

... 指令通常需要访问一些父范围属性。对象哈希用于在父作用域和隔离作用域之间建立双向绑定(使用'=')或单向绑定(使用'@')。还有 '&' 绑定到父范围表达式。因此,这些都创建了从父范围派生的本地范围属性。请注意,属性用于帮助设置绑定——您不能只在对象哈希中引用父范围属性名称,您必须使用属性。例如,如果您想在隔离范围内绑定到父属性 parentProp:和范围:{ localProp:'@parentProp'},这将不起作用。必须使用属性来指定指令要绑定到的每个父属性:和范围:{ localProp: '@theParentProp' }。

我认为,这应该更好地解释in the book 我正在阅读,它将链接描述为隔离范围和父范围之间的链接。事实上,这是使用 中间阶段完成的:隔离范围 指令属性 父范围

Umur Kontaci 还为此主题创建了some helpful examples

【讨论】:

    猜你喜欢
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 2015-05-14
    • 2011-04-23
    • 1970-01-01
    相关资源
    最近更新 更多