javascript - How to update an arrays (angularjs) element without splice? -
i having situation in post here not need fetch element, change e.g. name value.
i found out 1 that:
datalist.splice(index, 1); datalist.splice(index, 0, newitem);
but there several problems. know id if manipulating array time time loose track of index <=> id correlation because method take out items, change them , push them "new" one, right? kind of not elegant , cause problems think.
basically want toggle visible attribute should change in array. here array:
$scope.clines = [{ id: 1, ccolor: 'red', cname: 'entryline right', visible: true }];
of course there more elements inside, left 1 simplicity reasons.
the visible toggler should working (naiv "pseudocode" awesome if work simple :) )
$scope.clines[id === id].visible = !$scope.clines[id === id].visible;
second best thing if access element directly filter, possible?
thank in advance.
there several ways go it. 1 use filter()
.
var id = 1; var visibility = true; var items = $scope.clines.filter(function(item) { return item.id === id; }); if (items.length >= 1) items[0].visible = visibility;
you can wrap function:
function setvisibility(arr, id, visibility) { var items = arr.filter(function(item) { return item.id === id; }); if (items.length >= 1) items[0].visible = visibility; }
then use this:
setvisibility($scope.clines, 1, true);
you update $scope.clines
more complex object, instead of array:
$scope.clines = { "item" : function (id) { var items = this.lines.filter(function(item) { return item.id === id; }); if (items.length >= 1) return items[0]; else return new object(); //or throw error }, "lines" : [ { id: 1, ccolor: 'red', cname: 'entryline right', visible: true } //....and more ] };
then use this:
$scope.clines.item(1).visible = true;
with this, make sure use $scope.clines.lines
if have loop through it.
Comments
Post a Comment