DaveC426913
DaveC426913

Reputation: 2046

passing objects in Angular

I know that passing objects in Angular is the same as passing objects in vanillaJs, what's stumping me is why my model is not being updated.

I have bins that contain packages. Given a packageId, I need to find the bin it's in, and remove the package from it.

    vm.Bins = []; // bins of packages

    vm.debinPackage = function (packageId) {
        var bin = vm.getBin(packageId);
        var packagge = vm.getPackage(packageId, bin.Packages);
        vm.removePackageFromBin(packagge, bin);
    };

    vm.getBin = function (binId){
        return $filter('filter')(vm.Bins, function(bin, index) {
                  return bin.Id == binId;
        })[0];
    }; 

    vm.getPackage = function (packageId, packages) {
        return $filter('filter')(packages, function(packageItem, index) {
             return packageItem.Id == packageId;
        })[0];
    };

    vm.removePackageFromBin = function (packagge, bin) {
        bin = $filter('filter')(bin.Packages, function(packageItem, index) {
            return packageItem.Id != packagge.Id;
        }); 
    };

.

<button ng-click="adminManifestVm.debinPackage(packageId)"></button>

{{ adminManifestVm.Bins }}

So, vm.Bins in my controller, and consequently adminManifestVm.Bins in my view don't update to reflect the package that's been removed from the bin.

i.e. this line:

vm.removePackageFromBin(packagge, bin);

does not actually result in an updated vm.Bins object.

I think the problem is that, when I get the bin object I use var as a holder:

var bin = vm.getBin(packageId);

and that it is somehow detached from my vm.Bins object.

but I can't figure out how to manipulate the actual object in vm.Bins.

I tried operating on the object directly, rather than through the var

    vm.debinPackage = function (packageId) {
        var binId = vm.getBinIdWithPackage(packageId);
        var packagge = vm.getPackage(packageId, vm.getBin(binId).Packages);
        vm.removePackageFromBin(packagge, vm.getBin(binId));
    };

but not only does that not work, it starts to make my code unreadable.

How do I ensure that the bin object I am operating on is the one that's in vm.Bin, as opposed to some copy of it?

Upvotes: 0

Views: 48

Answers (1)

Graham S
Graham S

Reputation: 176

Have you tried using splice to remove the item from the array instead of reassigning the array with the filtered list?

vm.removePackageFromBin = function (package, bin) {
    var idx = bin.indexOf(package);
    bin.splice(idx, 1);
};

Upvotes: 1

Related Questions