Angular: How to $broadcast from Factory?

前端 未结 4 1151
没有蜡笔的小新
没有蜡笔的小新 2021-01-20 16:59

I have a list of items and I need to get a message (saying Item added!) in the navbar whenever a new item is added.

The function addItem() (ng-click on the Add Item

4条回答
  •  野性不改
    2021-01-20 17:38

    You can inject $rootScope into your factory and use $broadcast from there.

    angular.module('MyApp').factory('ItemFactory', ["$rootScope", function($rootScope){
    
        var items = [
            'Item 1', 
            'Item 2', 
            'Item 3'
        ];
    
        return {
            getItem : function() {
                return items;
            },
            addItem : function(item){
                items.push(item);
                // $broadcast
                $rootScope.$broadcast('itemAdded', 'Item added!');
            },
            removeItem : function($index){
                items.splice($index, 1);
            }
        };
    

    }]);

提交回复
热议问题