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" />
我的问题是&#34;数据点&#34;不受约束$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 */
};
});
我缺少什么或者什么是更好的方法来获得我的指令来获得控制器的范围数据点?谢谢。
答案 0 :(得分:2)
您可以在指令中使用隔离范围。
以下是AngularJS official documentation的一个例子。
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
通过继承访问控制器中的变量。