Search code examples
arraysangularjsdevextreme

Why array save last data and doesn't clears?


I have a simple AngularJs application of medical cards.

I have storage with it and display it at my home.html using dx-datagrid:

enter image description here

One card has many records, I get records of card from recordsArray by cardId

 getVardsRecordsByCardId: function (id, recordsArray) {
        if (recordsArray.length != 0) {
            for (var i = 0; i < recordsArray.length; i++) {
                if (recordsArray[i].cardId === id) {
                    cardsRecords = cardsRecords.concat(recordsArray[i]);
                }
            }
        }

        return cardsRecords;

    }

Now I have records just in the third card. I added a function on button for testing it:

 var jdskla = [];
var localCardId = 0;
$scope.showCardDetails = {
    text: "",
    type: "default",
    icon: "preferences",
    onClick: function () {
        if ($scope.itemIdFromShowButton) {
            $location.path('/carddetail/' + $scope.itemIdFromShowButton);
            var jdskla =[];
            var jdskla = businessLogicOfMyApp.getVardsRecordsByCardId($scope.itemIdFromShowButton, $scope.recordsArray);
            console.log($scope.itemIdFromShowButton)
            console.log(jdskla);

        }
        else {
            alert("Error!!!");
        }
    }
};

enter image description here

1,3,1 is cardId's and array of records. But, why array of card records don't clears and save last data?

May be somebody know how I can resolve it? Thanks for your answers!

P.S. I'm using ng-view directive in my app and i tried to clear my array use another button:

 $scope.backToGeneralPage = {
    text: "Back",
    onClick: function () {
        jdskla = [];
        $location.path('/');
    }
};

but it wasn't helpful.


Solution

  • You should initialize cardsRecords array in function getVardsRecordsByCardId.

     getVardsRecordsByCardId: function (id, recordsArray) {
        var cardsRecords = []; // initialize array locally
        if (recordsArray.length != 0) {
            for (var i = 0; i < recordsArray.length; i++) {
                if (recordsArray[i].cardId === id) {
                    cardsRecords.push(recordsArray[i]);
                }
            }
        }
        return cardsRecords;
    }