Reputation: 563
I am creating project using angularjs.I have problem while creating custom directive.Actually I want to send the value from controller to directive but I got undefined. Here is my code:
Here is Directive
.directive('angularData', function ($parse) {
return {
template: false,
scope: {
chart: '=lineChartData'
},
restrict: 'EA',
replace: true,
link: function postLink(scope, element,attrs) {
var canvas, context, chart, options;
console.log(attrs)
console.log(scope.chart) //undefiend
console.log(chart) //undefiend
}
};
});
Here is Html where I call the Directive
<canvas id="test" angular-data ="lineChartData" height="450" width="600"></canvas>
Here is controller Code
$scope.lineChartData = {
labels :[1,4,8,6,8],
datasets : [
{
label: "My First dataset",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [1,4,8,6,8]
}
]
}
Upvotes: 1
Views: 3170
Reputation: 4681
inside you DOM element pass your $scope variable like this: chart = lineChartData
hope this helps,gokd luck.
Upvotes: 0
Reputation: 856
In you html try this,
<canvas id="test" angular-data line-chart-data="lineChartData" height="450" width="600"></canvas>
It should work
Upvotes: 0
Reputation: 5977
Why aren't you declaring the controller inside the directive? That way it will have access to the data from the controller ... I.e.,
return {
template: false,
scope: {
chart: '=lineChartData'
},
controller: SomeController,
controllerAs: 'vm',
...
Then you have access to the controller's data via the scope on the directive's link.
Upvotes: 0
Reputation: 14648
Inside the link
function in your directive, put a watcher:
angular.module('myApp', []);
angular.module('myApp').directive('angularData', function ($q, $parse) {
return {
//template: false,
restrict: 'A',
//replace: true,
link: function postLink(scope, element,attrs) {
scope.$watch(attrs.angularData, function(value) {
console.log(value);
});
}
};
});
angular.module('myApp').controller("myCtl", function($scope) {
$scope.lineChartData={a:2, b:"test"};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtl">
<canvas id="test" angular-data ="lineChartData" height="450" width="600"></canvas>
</div>
</div>
Upvotes: 4