angularjsangularjs-directiveangularjs-controllerangularjs-componentsangularjs-bindings

AngularJS component binding a function


Let's say, we were trying to delete an item from the list using the web api.We had created a child component named as remove-item using parameters - item and onRemove.On click of a item,we would like to trigger the callback function to the parent component.As per the code,onRemove is not getting called after deleting the item.Can someone help us figure out the error and provide us the right solution with an illustration.

remove.component.js
-------------------
this.RemoveItem = function (index) {
            var promise = productList.removeItem(parseInt(this.id));
            promise.then(function (response) {
                console.log("An item has been deleted");
                this.items=response.data;
            }, function (error) {
                console.log("An error has occurred while deleting the item:", this.id);
               
            });
            this.onRemove({
                $index: this.items
            });       
        }


Solution

  • I would avoid using 'this'. Not sure why you passed index param in RemoveItem fn , can't see you use it anywhere in this scope. Anyway if productList.removeItem returns Promise than we can call onRemove. I would def need more information - html code and your remove fn code but try this anyway.

      let vm = this;
      vm.RemoveItems = RemoveItem;
      vm.onRemove = onRemove;
    
      RemoveItem(index) {
                    productList.removeItem(parseInt(this.id))
                    .then(function (response) {
                        console.log("An item has been deleted");
                        vm.onRemove({$index: response.data});
    
                    }, function (error) {
                        console.log("An error has occurred while deleting the item:", this.id);
    
                    });      
                }
      onRemove(obj) {
        console.log(obj); 
    //make your remove here
      }