属性内的角度指令范围继承
Angular Directive scope inheritance inside attributes
AngularJS新手问题。我想写一个绘图指令。假设我有这个:
app.controller("dirCtrl", function($scope) {
$scope.datapoints = [
{ x: 1.169, y: 1.810, label: "Point-0" },
{ x: 1.585, y: 0.508, label: "Point-1" },
{ x: 7.604, y: 2.735, label: "Point-2" },
...
];
});
那么我希望我的指令是这样的:
<my-plot xLabel="Some Numbers" xUnits="grams"
yLabel="Some Values" yUnits="mm"
data="datapoints" />
我的问题是"数据点"没有绑定到$scope.datapoints
我也尝试将属性编写为data="{{datapoints}}"
也没有成功。
我的指令定义,在其自己的模块中:
angular.module("plotDirectives", [])
.directive("myPlot", function() {
return {
restrict: "E",
scope: true, //'cos I want access to the controller's scope right?
link: function(scope, iElement, iAttrs) {
/* would draw fancy chart if I only could access
the datapoints in the 'data' attribute */
};
});
我缺少什么,或者我的指令获取控制器范围数据点的更好方法是什么?谢谢。
您可以在指令中使用隔离作用域。
这是来自AngularJS官方文档的示例。
angular.module('docsIsolateScopeDirective', [])
.controller('Controller', ['$scope', function($scope) {
$scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
$scope.igor = { name: 'Igor', address: '123 Somewhere' };
}])
.directive('myCustomer', function() {
return {
restrict: 'E',
scope: {
customerInfo: '=info'
},
templateUrl: 'my-customer-iso.html'
};
});
<div ng-controller="Controller">
<my-customer info="naomi"></my-customer>
<hr>
<my-customer info="igor"></my-customer>
</div>
如果你在指令中使用scope: true
(这在大多数情况下是一种不好的做法,因为它使指令与控制器非常紧密地耦合),你不需要在 DOM 上为你的指令设置属性,只需使用 scope.yourVariableName
通过继承访问控制器中的变量。
相关文章:
- AngularJS指令范围约束问题重复出现
- AngularJS:从控制器访问特定的指令范围
- 隔离范围-仅在指令范围内定义的值必须执行更改
- 指令范围
- 在ng重复中使用时的指令范围
- 角度指令模板输入不会更新指令范围
- 属性内的角度指令范围继承
- AngularJS:如何在指令范围的对象发生变化时更新与控制器作用域相关联的控制器作用域
- 如何从父指令/控制器访问指令范围
- AngularJS:在成功的HTTP请求后更新指令范围
- 购物指令范围问题
- 角度指令范围为空
- 在指令“范围”中需要值属性
- AngularJS 指令范围和$compile - 返回空白的变量
- AngularJS指令范围似乎只接受一个参数
- AngularJS :如何从相同的指令控制器访问指令范围
- 通过指令范围传递对象不起作用
- 指令范围重写父值
- 角度指令 - 范围返回 0 而不是值
- AngularJS 父指令范围来自内部 ng-transclude