Reputation: 61
AngularJS newbie question. I want to write a plotting directive. Let's say I have this:
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" },
...
];
});
Then I would like my directive to be like this:
<my-plot xLabel="Some Numbers" xUnits="grams"
yLabel="Some Values" yUnits="mm"
data="datapoints" />
My problem is that "datapoints" does not get bound to $scope.datapoints
I've also tried writing the attribute as data="{{datapoints}}"
without success either.
My directive definition, in its own module:
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 */
};
});
What am I missing or what would be a better approach for my directive to get to the controller's scope datapoints? Thank you.
Upvotes: 2
Views: 52
Reputation: 3056
You can use an isolate scope in your directive.
Here's an example from 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>
If you use scope: true
in your directive (which is most of the time a bad practice, as it makes the directive very tight coupled to the controller), you don't need to set attributes on the DOM for your directive, just use scope.yourVariableName
to access variables in the controller by inheritance.
Upvotes: 2