我有一个服务,它在页面加载时最初被调用,并根据我的自定义指令的构造结果,当构造 DOM 时,我想再调用一个服务,第一个结果中的一些数据应该传递到该服务并基于该服务对于这个结果我想更新已经构建的 DOM。例如,构建学生数据,然后调用新服务来传递学生 ID 以获得出勤状态,并根据收到的数据,我想显示绿色或红色图像(已经在 DOM 中,但需要显示/隐藏它) .
- 正确的做法是什么?
- 第二个服务的结果是一个json对象,我如何根据ID添加类?
第一指令
<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>
....
第二次服务结果
{
"status": [{
"id": 1,
"stat": "true"
}, {
"id": 2,
"stat": "false"
}, {
"id": 3,
"stat": "false"
}, {
"id": 4,
"stat": "true"
}]
}
最佳答案
您可以通过以下方式做到这一点;
<div class="led"
style="position:absolute"
ng-class="{ 'green': status[std.id], 'red': !status[std.id] }">
您应该使用以下内容更新您的 StudentViewDirectiveCtrl;
angular.module('adf.widget.student')
.controller('studentViewDirectiveCtrl', ['$scope', 'secondService',
function($scope, secondService) {
function organiseStatus(status) {
var returnMap = {};
for (index in status) {
var statu = status[index];
returnMap[statu.id] = statu.stat == 'true' ? true : false;
}
return returnMap;
}
secondService.getStatus($scope.ids)
.then(function(result) {
$scope.status = organiseStatus(result.status);
})
.catch(function() {
/* error :( */
});
}
]);
关于javascript - Angular JS : How do i call a second service from controller and update the DOM with returned Object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37885496/