Angular - Passing scope data to directive
HTML
<div ng-app="testapp">
<div ng-controller="Ctrl">
<h1>Test of Directive</h1>
<button ng-click="broadcast_ts()">Get Data</button>
<chart-dir num='1'></chart-dir>
<chart-dir num='2'></chart-dir>
<chart-dir num='3'></chart-dir>
</div>
</div>
CSS
.class1
{
color:blue;
}
.class2
{
color:red;
}
.class3
{
color:yellow;
}
JavaScript
var app = angular.module('testapp', [])
.controller('Ctrl', Ctrl);
function Ctrl($scope) {
$scope.ts = -1; // timestamp
$scope.broadcast_ts=function()
{
$scope.$broadcast('hello',{"values":'class1'})
}
}
app.directive('chartDir', function () {
return {
restrict: 'EA',
scope: {
num: '@'
},
replace: true,
template: '<div ng-class="getClass()"><h3> {{getClass()}} :: Chart {{num}}</h3><p>Time Stamp: {{ts}}</p></div>',
controller : function($http, $scope, $element, $attrs) {
$scope.getClass = function (person) {
return $scope.main;
};
},
link: function (scope, element, attrs) {
scope.main="class1";
scope.$on('hello', function(event, args){
console.log("DATA RECEIVED", scope.num);
scope.main="class" + scope.num;
});
}
};
});