我有一个简单的应用程序来跟踪客户:姓名(和/或 ID)和开始时间。它还显示每个客户的总时间,并根据客户花费的时间显示账单。
我最初是用 vanilla JS 编写的应用程序,但现在我用 Angular 重写它。我无法想出更新 View 中总时间的好方法。这是我目前所拥有的:
型号:
.factory('Customer', function () {
function Customer(id, name, start, discount) {
this.name = name || '';
this.id = id || null;
this.start = start || Date.now();
this.discount = parseFloat(discount) || 0;
this.orders = [];
}
Customer.prototype.addOrder = function (order) {
this.orders.push(order);
};
Customer.prototype.deleteOrder = function (order) {
var index = this.orders.indexOf(order);
if (index > -1) {
this.orders.splice(index, 1);
}
else {
console.log('Order deletion error - order not found.');
}
};
Customer.fromObj = function (obj) {
return new Customer(
obj.id,
obj.name,
obj.start,
obj.discount)
};
return Customer;
})
Controller 部分:
$scope.addCustomer = function () {
// add current time
$scope.newCustomer.start = Date.now();
// push the customer to container
$scope.customers.push(Customer.fromObj($scope.newCustomer));
}
查看:
<tr ng-repeat="customer in customers" ng-click="customerDetails(customer)">
<td ng-bind="customer.name"></td>
<td ng-bind="customer.id"></td>
<td>SHOW TIME HERE</td>
<td>SHOW MONEY HERE</td>
</tr>
问题:
最初,我每个客户对象都有自己的更新时间和金钱值的间隔,如下所示:
this.timeTotal = 0;
this.moneyTotal = 0;
this.timeInterval = setInterval(this.updateTime.bind(this), 1000);
this.moneyInterval = setInterval(this.updateMoney.bind(this), 1000);
以及清除销毁间隔的功能:
Customer.prototype.clearIntervals = function(){
clearInterval(this.timeInterval);
clearInterval(this.moneyInterval);
}
这样,我就可以<td ng-bind="customer.timeTotal">
。 但是,我相信,时间/金钱跟踪应该在 View 中进行(我错了吗?)。到目前为止我发现的示例似乎都在谈论使用 $interval
更新单个值.
我正在考虑一些可能的解决方案:
- 创建一个类似
<td track-time="customer">
的指令 - 使用父 Controller 中的某种函数来实现
- 使用旧方法,每个对象都有一个时间间隔和一个存储 timeTotal 的属性
- 使用事件
- 也许还有其他什么?
我希望您能帮助我选择一个似乎更适合这种情况的决定,或者您可以建议我还没有想到的其他方法。
请注意,唯一需要备份到存储的字段是 name
, id
, start
, discount
,这就是我不愿意向 Customer
添加更多属性的部分原因。类。
最佳答案
更新 View 模型最好在 Controller 中完成。
如果您为每个客户创建一个指令(如果您使用的是 Angular 1.5,则为组件),那么他们每个人都有自己的范围,您可以在其中处理间隔。
<div ng-repeat="customer in customers" ng-click="customerDetails(customer)">
<customer customer-ref="customer"></customer>
</div>
客户Ctrl:
$interval(updateTime, 1000)
function updateTime(){
// $scope.time = $scope.customer.foo etc...
}
您应该使用 $interval 而不是 setInterval。
关于javascript - 在 Angular 中按时间间隔更新 View 中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39568078/