【发布时间】:2018-02-01 21:14:05
【问题描述】:
我在 angularjs 中有一个由 mysql 表组成的数组,我用 php 将它返回到 json 并在 angularjs 中获取它。我在 ionic 中创建了一个应用程序并使用了 angularjs。我可以删除项目、插入项目和编辑项目。项目具有属性优先级,我希望优先级是唯一的。因此,在添加项目时,我正在检查最后添加的 item.priority,下一个具有优先级 + 1。在项目删除时,我检查 item.priority,以便下一个添加的项目将优先级设置为已删除项目的优先级。但例如我有 6 个项目,我删除了 item4,所以下一个添加的项目将具有优先级 4,但是当我添加下一个时,它的优先级为 5,但我已经有 5,所以我想将优先级设置为 7,因为我有 6 个项目。所以我尝试的是:
$scope.priority = Math.max(parseInt($rootScope.obiadki.priority));
但它返回未定义。我的问题是,如何检查整个数组中所有对象的优先级属性的最大值。
我如何检索数据:
$scope.getData = function () {
$http({
method: 'get',
url: 'mygetdatacodeurl'
}).then(function successCallback(response) {
// Store response data
$rootScope.obiadki = response.data;
$scope.checkPriority();
});
};
我如何检查优先级:
$scope.checkPriority = function () {
$scope.priority = Math.max(parseInt($rootScope.obiadki.priority));
};
我如何检查 addItem 的优先级:
$scope.checkPriorityOnAdd = function () {
$scope.priority = parseInt($scope.priority) + 1;
};
我的 addItem 函数:
$scope.addItem = function() {
$http({
method: "post",
url: 'myinsertcodeurl',
data: {
id: $scope.id,
obiad_name: $scope.obiad_name,
active: $scope.active,
priority: $scope.priority
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
$scope.getData();
$scope.checkPriorityOnAdd();
};
我设置删除优先级的 deleteItem 函数:
$scope.onItemDelete = function(item) {
$http({
method: "post",
url: 'mydeletecodeurl',
data: {
id: item.id
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
$scope.getData();
$scope.priority = item.priority;
};
【问题讨论】:
-
你试过什么? “for”循环? Array.forEach()?
-
您没有包含相关数据。请更新您的问题以包含
$rootScope.obiadki。 -
it's not recommended 填充您的
$rootScope。 如何返回你的 json? -
我尝试过使用 Math.max,但效果不佳。我将尝试使用 forEach 循环。
-
为什么不将数据存储在一个数组中,并使用数组中的每一项作为其优先级?
标签: javascript angularjs