I am trying to learn the Angular way of adding a DOM element with data returned from the service passing it to a directive by changing the scope variable from my controller.
My service
.factory('Poller', function($http,$q){
return {
poll : function(api){
var deferred = $q.defer();
$http.get(api).then(function (response) {
deferred.resolve(response.data);
});
return deferred.promise;
}
}
});
My Controller
.controller('accordion',['$scope','Poller','$timeout',function($scope,Poller,$timeout){
$scope.newdata = null;
function Repeater () {
$scope.$apply(function () {
Poller.poll('api/getupdates')
.then(function(data){
$scope.newdata = data;
});
});
};
$timeout(Repeater, 1000) ;
var timer = setInterval(Repeater, 11000);
My Directive
.directive( 'newreading', function () {
return {
scope: {'newdata' : '='},
templateURL : 'template\newreading.html',
link: function ( scope, element, attrs ) {
var el;
scope.$watch('newdata', function () {
console.log(scope.newdata);
});
}
};
});
HTML //NOTE: this is done by ng-repeat
<accordion-group id="Device 1">
<newreading ></newreading>
</accordion-group>
<accordion-group id="Device 2">
<newreading ></newreading>
</accordion-group>
<accordion-group id="Device3">
<newreading ></newreading>
</accordion-group>
<accordion-group id="Device4">
<newreading ></newreading>
</accordion-group>
My Sample JSON
{
"readings": [
"id": "Device2",
"T01": "3",
"L02": "35"
]
}
Everything til here works fine, and I want to stay away from using jQuery at all (I know Angular has jQuery Lite)
My Question
Firstly, Is this the right approach to add an element to the DOM using Angular JS? If yes, how will I reuse this directive? Currently, scope.watch triggers the function 4 times (obviously!!).
I am too confused because I cannot find a simple way to trigger the right directive to add an element.
I have been through few parts of the documentation and found StackOverflow questions suggesting to compile and add elements, which I can do but I need to add the element in the required div.
Any help is much appreciated.