我正在學習AngularJS,並且正在閱讀有關將指令的父範圍的變量綁定到指令的隔離範圍的方法。我對範圍層次結構有一些理解問題。定義Angular指令時的父子範圍層次結構
有簡單和工作顏色選擇器指令例如:
的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],然後將其發送到指令進行更改,然後再次將其返回給控制器以獲取範圍結果。 – Maher
感謝您的回覆,但在此示例中沒有使用明確模型聲明($ scope.x)的控制器。我剛剛在AngularJS書中找到了這個例子。 – karlitos