Answer the question
In order to leave comments, you need to log in
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();
});
<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>
var srv = new TestSrv();
TypeError: object is not a function
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question