Firebase's AngularFire in an AngularJS service

别等时光非礼了梦想. 提交于 2019-12-03 07:02:57

If you want to encapsulate some of the functionality into a service, consider keeping the returned ref in state of the service. I expanded on your plunker. It seems to mostly do what you were trying for.

http://plnkr.co/edit/Uf2fB0

Jeff answered the question correctly ... I'm just posting a further development on Jeff's example for those who are interested.

I have abstracted the Firebase service creation, so you can dynamically create an instance of whatever Firebase service you want:-

var registerFirebaseService = function (serviceName) {
    app.factory(serviceName, function (angularFire) {
        var _url = null;
        var _ref = null;

        return {
            init: function (url) {
                _url = url;
                _ref = new Firebase(_url);
            },
            setToScope: function (scope, localScopeVarName) {
                angularFire(_ref, scope, localScopeVarName);
            }
        };
    });
};

You first create an instance of the service as follows

registerFirebaseService('itemsService'); // create itemsService instance

Then you can inject the itemsService service into your controllers. The instance is initialised using your Firebase URL e.g.

itemsService.init('https://firebase.firebaseio.com/' + userId + '/items');

The Firebase can now be bound to your controller e.g.

itemsService.setToScope($scope, 'items');

adapted PLUNKER

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!