我的控制器中有两个功能,如下所示。
$scope.formatPaymentDates = function() {
$scope.formatDate($scope.payment.due_date);
$scope.formatDate($scope.payment.date);
};
$scope.formatDate = function(attr) {
if (attr) {
var split_date = attr.split("-");
if (split_date[0].length == 4) {
attr = split_date[1] + "-" + split_date[2] + "-" + split_date[0];
} else {
attr = split_date[2] + "-" + split_date[0] + "-" + split_date[1];
}
}
};
问题是函数formatDate只设置范围变量属性而不保存它。我错过了什么?
答案 0 :(得分:1)
在JavaScript中,字符串和数字按值传递,而对象则通过引用传递。您应该传递一个对象作为参数。
或者,正如@faby提到的那样,返回值:
$scope.formatPaymentDates = function() {
$scope.payment.due_date = $scope.formatDate($scope.payment.due_date);
$scope.payment.date = $scope.formatDate($scope.payment.date);
};
$scope.formatDate = function(attr) {
var result;
if (attr) {
var split_date = attr.split("-");
if (split_date[0].length == 4) {
result = split_date[1] + "-" + split_date[2] + "-" + split_date[0];
} else {
result = split_date[2] + "-" + split_date[0] + "-" + split_date[1];
}
}
return result;
};
答案 1 :(得分:1)
问题是您没有从formatDate函数返回任何结果。 您正在操作函数内部的变量,然后销毁它。
试试这个
$scope.formatDate = function(attr) {
if (attr) {
var split_date = attr.split("-");
if (split_date[0].length == 4) {
attr = split_date[1] + "-" + split_date[2] + "-" + split_date[0];
} else {
attr = split_date[2] + "-" + split_date[0] + "-" + split_date[1];
}
return attr;
}
return null
};
然后
$scope.formatPaymentDates = function() {
$scope.payment.due_date= $scope.formatDate($scope.payment.due_date);
$scope.payment.date=$scope.formatDate($scope.payment.date);
};