angularjsangularjs-components

What is the alternative of $apply in AngularJS Component


When I remove items from items list. It takes time to refresh on the browser. I am unable to found any alternate of $apply(). It's a callback function when call the component object from outside the component.

import template from './itemListItems.html';

export const name = 'itemListItems';
export const itemListItems = {
    template,
    bindings: {
        listItems: '<',
        addNewItem: '&',
        editItem: '&',
    },
    controller: class ItemListItemsController {
        // @ngInject
        constructor(page) {
            this.page = page;
        }
        removeItem(indx) {
            var func = function (button) {
                if (button === 1) {
                    this.listItems.splice(indx, 1);// After removing itemlist, 
it takes few seconds to refresh on browser.                
                  }
            };
            navigator.notification.confirm(
                'Are you sure you want to remove this item?',
                func.bind(this),
                'Confirm Delete',
                ['Confirm', 'Cancel']
            );
        }
    }
};

I have issue on this line. this.listItems.splice(indx, 1); After removing itemlist, it takes few seconds to refresh on browser. Previously in directove mode, I was using $scope.$apply(). But in component, $apply is no more available. What is the solution please?


Solution

  • No need to refresh the page. If you already initialize the array in the parent component, it should update automatically, since the array is a reference type.

    The better way, is to use '&' binding, like your 'addNewItem' and 'editItem'.

    It should look like this:

    export const itemListItems = {
        template,
        bindings: {
            listItems: '<',
            addNewItem: '&',
            editItem: '&',
            onRemove:'&',
        },
        controller: class ItemListItemsController {
            // @ngInject
            constructor(page) {
                this.page = page;
            }
            removeItem(indx) {
                var func = function (button) {
                    if (button === 1) {
                        this.listItems.splice(indx, 1);
                        this.onRemove(indx);
    
                      }
                };
                navigator.notification.confirm(
                    'Are you sure you want to remove this item?',
                    func.bind(this),
                    'Confirm Delete',
                    ['Confirm', 'Cancel']
                );
            }
        }
    };
    

    Parent- HTML:

    <item-list-items list-items="yourlist" on-remove="removeFromList($event)"></item-list-items>
    

    Parent-controller js:

    //...
    $scope.removeFromList = function (index) {
        $scope.yourlist.splice(index, 1)
    }
    //...