F
F
Fedor2015-03-13 10:31:24
Angular
Fedor, 2015-03-13 10:31:24

What is the correct way to create a new service instance for the controller?

Hello everyone,
looking at
https://github.com/mgechev/angularjs-in-patterns#s... I
made this code in main.js:

angular
    .module('app',[])
    .factory('TestSrv', function(){
         var 
            buf,
            factory= {
                setBuf: setBuf,
                getVal: getVal
            };

         return factory;

         function setBuf(val){
            buf = val;
         };

         function getVal(){
            console.log(buf);
         };


    })
    .controller('main',function(TestSrv){
        var srv = new TestSrv();
        srv.getVal();
        srv.setBuf('fff');
        srv.getVal();

    })
    .controller('main2',function(TestSrv){
        var srv = new TestSrv();
        srv.getVal();
        srv.setBuf('fff1');
        srv.getVal();

    });

in index.html
<html lang="en" ng-app="app">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <div ng-controller='main' >
        </div>
        <div ng-controller='main2' >
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script>
        <script src="./js/main.js"></script>
    </body>
        
</html>

swears at the line
var srv = new TestSrv();
error:
TypeError: object is not a function

strange, in the example on github-e, is everything the same or am I still doing something wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2015-03-13
Protko @Fesor

Read about constructor functions. You cannot apply new to a hash map. http://learn.javascript.ru/object-methods#function-...
As for your task... All services in Angular come in a single copy. If you need services to store different states for different controllers, either implement the factory template yourself and inject the service factory directly into the controllers, or implement something like registry.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question