javascript - How to use an angular factory correctly? -
I am reading enough about sensory dependency injection and factory vs. services like this post - < P> I am struggling to put it in practice and am surprised if you can suggest me how you will do it.
My current code looks like this
var app = angular Modules ("Martisk Coolap", ['Firebase', 'NGRUT']) Function Main Controller ($ Scope, $ Firebase) {var db = New Firebase ("https: //**.firebaseio.com/"); $ Scope.messages = $ firebase (db); $ Scope.addItem = function (error) {if (error.keyCode! = 13) returns; $ Scope.messages $ Add ({name: $ scope.name, price: $ scope.price}); $ Scope.name = ""; $ Scope.price = ""; }; } I decided that I want to use angular routes and divide this basic function into two separate controllers which I will use for my test app. The main controller will only show everything in Firebase DB and the admin controller will be able to add the message to it var app = angular Modules ("Maltese Cool app", ['Firebase', 'NGRUT']). 'Firebase Connection Connection', $ Firebase) // Code to connect to Firebase and add message here. Controller ('Main Controller', Function (Firebase connection connection, $ range, $ route, $ route param, $ location) {$ scope $ route = $ route; $ scope. $ Location = $ location; $ scope. $ RouteParams = $ RouteParams; // code to get everything from firebase db}). Controller ('AdminController', Function (fireBaseConnectionService, $ scope, $ RouteParams) {$ scope.name = "AdminController"; $ scope.params = $ routeParams; // to add a line in code to DB}). When configuring ('$', '$') ({$ route provider, $ location provider} {$ routeProvider ('/', {redirectTo: '/ menu'}) .When ('/ menu', {path: '/ menu', template url: 'partial / Menu ('html', controller: 'main controller'}). ('/ Admin', {templateUrl: 'parti als / admin.html', administrator: 'AdminController'}). Otherwise ({redirectTo: '/'}) ; $ LocationProvider.html5Mode (wrong);}); My problem is that I do not want to connect to Firebase db in each controller. I want a factory which handles it for me and maybe there is a function within it that I can call my controllers to see everything in DB and call DB to add something
< Div class = "post-text" itemprop = "text">
All you have to do is just transfer the firebase connection to the service, and take that service wherever you want. When your app runs, you will run your app for the first time for a connection, seeing that you are coming forward:
.factory ('fireBaseConnectionService', function ($ Firebase) {Var db = $ firebase (newfirebase ("https: //**.firebaseio.com/")) // create // firebase connection executes this line only once, when service returns {if you service script dynamic If you load it on the root, where you need it, it will only connect to the database when it hits it Reaches c make a connection to the above address database, because the connection line is only executed once.
Comments
Post a Comment