Upon the page loading, my Service is activated and constructs a custom directive based on the result. After the DOM is constructed, I need to call another service and pass some data from the initial result. With the new data received, I wish to update the existing DOM accordingly. For example, Student data is initially constructed, then a new service is called with the student ID to retrieve Attendance status. Based on this data, I want to display either a Green or Red image (which already exists in the DOM but needs to be shown/hidden).
- What is the correct approach for achieving this?
- The result of the Second service is a JSON object. How can I add a class based on the ID?
First Directive
<div ng-controller="studentCtrl">
<div ng-if="showTable">
<student-view></student-view>
</div>
</div>
Controller.js
angular.module('adf.widget.student')
.controller('studentCtrl', ['$scope', 'students',
function($scope, students) {
//students is service.
var data = students;
var key;
$scope.ids = [];
if (data.students.length > 0) {
$scope.students = data.students;
for (key in $scope.students) {
if ($scope.students[key]['id'] !== '') {
$scope.ids.push($scope.students[key]['id']);
}
}
$scope.showTable = true;
} else {
$scope.showTable = false;
}
}
]);
Directive.js
angular.module('adf.widget.student')
.directive('studentView', function(dashboard) {
return {
restrict: 'AE',
templateUrl: 'studentView.html',
replace: true,
controller: 'studentViewDirectiveCtrl'
}
})
studentViewDirectiveCtrl.js
angular.module('adf.widget.student')
.controller('studentViewDirectiveCtrl', ['$scope', 'secondService',
function($scope, secondService) {
secondService.getStatus($scope.ids)
.then(function(result) {
$scope.status = result.status;
})
.catch(function() {
/* error :( */
});
}
]);
studentViewTemplate.html
<div ng-repeat="std in students" class="student">
<img class="img-responsive" src="../rv/{{std .image}}" />
<div class="showLed">
<!-- How do i add red/green className based on the Second Service Result -->
<div class="led" style="position:absolute" class="red/green">
</div>
</div>
....
Result of Second Service
{
"status": [{
"id": 1,
"stat": "true"
}, {
"id": 2,
"stat": "false"
}, {
"id": 3,
"stat": "false"
}, {
"id": 4,
"stat": "true"
}]
}