我正在努力选择从控制器访问位于服务内部的集合的正确方法。我看到两种选择,都有起伏:
从返回集合的服务返回函数:
服务:
app.factory('healthService', function () {
var healths = [{},{},{},{}];
function updateHealths() {
healths = [...];
}
return {
getHealths : function() {
return healths;
},
update : function () {
updateHealths();
}};
});
控制器:
$scope.healths = healthService.getHealths;
$scope.update = healthService.update;
查看:
ng-repeat = "health in healths()"
ng-click = "update()" '
我不确定这里的效率 - 健康()的评估频率如何?
可直接从控制器访问集合:
服务:
app.factory('healthService', function () {
return {
healths : [{},{},{},{}],
update :function() {
this.healths = [...];
}
});
控制器:
$scope.healthService = healthService;
查看:
ng-repeat = "health in healthService.healths" '
ng-click = "healthService.update()"
哪一个更好,更快?还有其他提示吗?
答案 0 :(得分:1)
为什么不尝试将集合包装在对象(充当服务状态)中以允许在对象上进行绑定,而不是通过公开函数。例如:
app.factory('healthService', function() {
var state = {
healths: [...]
};
return {
getState: function() { return state; },
updateHealths: function() { state.healths = [...]; }
};
});
然后在你的控制器内:
$scope.healthState = healthService.getState();
然后从您的HTML引用您的健康状况,请使用:
<div ng-repeat="health in healthState.healths"></div>