getting service instance in controller - angularjs

I'm trying to get a service instance but am getting an error. I am getting the exception that Calculator.random() is not a function. Any idea what I'm doing wrong?
angular
.module('app')
.factory('Calculator',function(){
var random = {};
random.number = function (){
return Math.random();
};
return random;
});
angular
.module('app')
.controller('homeCtrl', ['$scope','Calculator', function ($scope,Calculator) {
$scope.random = Calculator.random();
}]);

You can try like this:
angular
.module('app').controller('homeCtrl', function($scope, Calculator) {
$scope.random=Calculator.number();//in your factory number holds the random function.
}
IN your case its breaking
reason: Calculator.random(); is not a function.

Like Cyril said, you define an object with a local name random in the calculator factory definition. You then return that object but that object has a property called number that points to a function not a property called random.
angular
.module('app', [])
.factory('Calculator',function(){
var random = {};
random.number = function (){
return Math.random();
};
return random;
});
angular
.module('app')
.controller('homeCtrl', ['$scope','Calculator', function ($scope,Calculator) {
$scope.random = Calculator.number();
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="homeCtrl">{{random}}</div>
</div>

This should work:
angular
.module('app', [])
.factory('Calculator', function () {
return function () {
return Math.random();
}
});`

Related

Angularjs - Can not load service returned value to $scope

I'm using angularjs and I am trying to parse a value from a service to my $scope controller. The problem is that is loading first the $scope and then the service. As a result me my scope is always undefinied. I tried many solutions that I found by no-one is worked for me. Can anyone help me please?
My service:
'use strict';
angular.module('myApp')
.service('getCategoriesService', function ($rootScope) {
getCategories = function () {
var categoriesByLocation = 1;
return categoriesByLocation;
};
and my controller:
angular.module("myApp")
.controller('MyCtrl', function ($scope,getCategoriesService) {
$scope.resultCategory = getCategoriesService.getCategories();
});
Use the this. when declaring a function in a service.
.service('getCategoriesService', function ($rootScope) {
this.getCategories = function () {
var categoriesByLocation = 1;
return categoriesByLocation;
};
})
demo
var app = angular.module("myApp",[]);
app.controller('MyCtrl', function ($scope,getCategoriesService) {
$scope.resultCategory = getCategoriesService.getCategories();
});
app.service('getCategoriesService', function ($rootScope) {
this.getCategories = function () {
var categoriesByLocation = 1;
return categoriesByLocation;
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
{{resultCategory}}
</div>
Change it as
angular.module("myApp")
.controller('MyCtrl', function ($scope,getCategoriesService) {
getCategoriesService.getCategories().then((function (d) {
$scope.resultCategory = d;
}
});

angularjs: not able to pass a variable value from controller to view

(function() {
angular
.module('myApp.home', [])
.factory('myService', function($http) {
return {
getInfo: function() {
// return something
}
};
})
.controller('HomeController', function($scope, $routeParams, myService) {
var my = this;
var sid;
myService.getInfo().success(function(data) {
my.id = data.id;
//sid= my.id;
});
//my.id = sid;
});
})();
I'm trying to access the variable id in my view. But I'm not able to do so. I'm getting an undefined variable error.
I even tried to declare a variable sid globally so that it can be accessed from everywhere and I tried assigning value to it as well but that effort also didn't bring up any results.
My services are working fine and they are returning data. I'm trying to use the id in my view but don't know where I messed it up.
Any help?
EDIT
And my HTML is like this:
<div data-id="my.id"></div>
If you want to use it in your view you have to bind it to a scope e.g. $scope.id - check this link for reference.
Below is your html, how it should be.
<div ng-app="app" ng-controller="HomeController as home">
<div data-id="home.id">{{home.id}}</div>
</div>
Below is how your controller part.
angular.module('app', [])
.controller('HomeController', function () {
this.id = "someValue";
});
http://jsfiddle.net/grdmLfxt/
use controllerAs : vm then you can access vm.id in your view.
HTML
<div ng-app="app" ng-controller="HomeController as vm">
<div data-id="vm.id">{{vm.id}}</div>
</div>
Controller
.controller('HomeController', function () {
var vm = this;
vm.id = "someValue";
});
for more info read this
small change in javascript code and html. try this.
Javascript
(function() {
angular
.module('myApp.home', [])
.factory('myService', function($http) {
return {
getInfo: function() {
// return something
}
};
})
.controller('HomeController', function($scope, $routeParams, myService) {
var my = this;
var sid;
myService.getInfo().success(function(data) {
$scope.id = data.id; // changed from my.id to $scope.id
//sid= my.id;
});
//my.id = sid;
});
})();
HTML
<div data-id="id"></div>

sharing data between controller in Angularjs is not clear

I created a common service to share the data between controller.
Below is the code snippet.
Here am getting undefined while using setter and getter. While accessing the object directly am getting the value. How to get the values using getter and setter.
what happens behind the scenes here.
// JavaScript source code
(function () {
'use strict';
angular.module('app',[])
})();
(function () {
'use strict';
angular
.module('app')
.factory('appcontext', appContext);
function appContext() {
var service = {
getStartDate: getStartDate,
setStartTime : setStartTime,
startTime : startTime
};
return service;
//private variables
var startTime = '';
function setStartTime(startTime) {
startTime = startTime;
}
function getStartDate() {
return startTime;
}
}
})();
(function () {
'use strict';
angular.module('app')
.controller("InsController", InsController)
InsController.$inject = ['appcontext'];
function InsController(appcontext) {
appcontext.setStartTime(new Date());
console.log(appcontext.getStartDate()); // undefined
appcontext.startTime = new Date();
console.log(appcontext.startTime); //prints the date correctly
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-App="app">
<div ng-controller= "InsController">
<div>{{ }}</div>
</div>
</html>
There is nothing wrong with your code. It is just the naming convention that is causing the conflict if I just replace your setStartTime method parameter name. Everything works well.
// JavaScript source code
(function () {
'use strict';
angular.module('app',[])
})();
(function () {
'use strict';
angular
.module('app')
.factory('appcontext', appContext);
function appContext() {
var service = {
getStartDate: getStartDate,
setStartTime : setStartTime,
startTime : startTime
};
return service;
var startTime = '';
function setStartTime(newStartTime) {
startTime = newStartTime;
}
function getStartDate() {
return startTime;
}
}
})();
(function () {
'use strict';
angular.module('app')
.controller("InsController", InsController)
InsController.$inject = ['appcontext'];
function InsController(appcontext) {
appcontext.setStartTime(new Date());
console.log(appcontext.getStartDate());
appcontext.startTime = new Date();
console.log(appcontext.startTime); //prints the date correctly
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-App="app">
<div ng-controller= "InsController">
<div>{{ }}</div>
</div>
</html>
You need to eliminate the startTime variable and reference is as service.startTime. You've created a property for it on your service, but the rest of your code references the var rather than the property.
function setStartTime(startTime) {
service.startTime = startTime;
}
function getStartDate() {
return service.startTime;
}
Not sure if this is all your code, but it looks like some of the uses of StartDate should be StartTime as well.
My this blog post may help you :
http://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/05/04/how-to-share-data-between-controllers-in-the-angularjs.aspx
Just return the functions you would like to expose. Since you have your getter and setter functions, don't return the variable itself, that wouldn't be much of a help. Create a variable service which stores every internal stuff you need and your functions should make use of that.
// JavaScript source code
(function () {
'use strict';
angular.module('app',[])
})();
(function () {
'use strict';
angular
.module('app')
.factory('appcontext', appContext);
function appContext() {
var service = this;
return {
getStartDate: getStartDate,
setStartTime : setStartTime
};
//private variables
service.startTime = '';
function setStartTime(startTime) {
service.startTime = startTime;
}
function getStartDate() {
return service.startTime;
}
}
})();
(function () {
'use strict';
angular.module('app')
.controller("InsController", InsController)
InsController.$inject = ['appcontext'];
function InsController(appcontext) {
appcontext.setStartTime(new Date());
console.log(appcontext.getStartDate()); // undefined
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-App="app">
<div ng-controller= "InsController">
<div>{{ }}</div>
</div>
</html>

How can I call the JS function which is defined in subpage?

In angularjs,I use the directive to contains the subpage into mainpage.
However, I found when I want to call the JS function in subpage, the browser always return back the information .
I wonder what can I do to fixed the errors.
Mainpage
var menuModule = angular.module('menuModule',[]);
menuModule.controller("MenuSettingController", function($scope, $http) {
initTree();
});
Subpage
<script type="text/javascript">
function initTree(){
console.log("in");
}
</script>
Thanks a lot.
If you want to call a function which are defined in subpage, you can wrap it into the current window object. Moreover, you can also wrap object into your window object.
Then, you can call your function, into your controllers for example.
Wrap function
Controller
(function(){
function Controller($scope) {
initTree();
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
Subpage
<script type="text/javascript">
(function(){
function init(){
console.log('init');
}
//Wrap our init function into our window object
window.initTree = init;
})();
</script>
Wrap object
But, as i said, you can wrap object to the window object, so you can do :
Controller
(function(){
function Controller($scope) {
//Call our init function
app_function.init();
//Call our setter
app_function.set(42);
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
Subpage
<script type="text/javascript">
//initialize our anonymous function with the app_function or an empty object
(function(app){
function init(){
console.log('init');
}
function set(n){
console.log('Set value : ' + n);
}
//Register our function
app.init = init;
app.set = set;
})(window.app_function = window.app_function || {});
</script>
Use angular services
Use angular services is a good practice, it will make your code more reusable and clean.
You have to know that all angular services are singletons. So, you can easily share common logic, data between controller.
Controller
(function(){
function Controller($scope, Service) {
//Call our init function
Service.init();
//Call our setter
Service.set(42);
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
(function(){
function Controller2($scope, Service) {
var old = Service.get();
//Retrieve 42
console.log(old);
//Call our init function
Service.init();
//Call our setter with new value
Service.set(++old);
var newValue = Service.get();
//Retrieve 43
console.log(newValue);
}
angular
.module('app')
.controller('ctrl2', Controller2);
})();
Service
(function(){
function Service() {
var data;
function init(){
console.log('init');
}
function get(){
return data;
}
function set(n){
data = n;
console.log('Set value : ' + n);
}
//Create our object with several method
var factory = {
set: set,
init: init,
get: get
};
return factory;
}
angular
.module('app')
.factory('Service', Service);
})();

Correct way to make a factory module in angularJs

I have a controller function like this:
$scope.localTimezone = function (userTimezone,datetime) {
// ....
return data;
}
What is the correct way to make it a factory module? I tried the following but it's giving errors.
angular.module('localTimezone', [])
.factory('localTimezone',function(userTimezone,datetime) {
// ...
return data;
});
angular.module('app', ['localTimezone'])
.controller('tasksController',function ($scope,localTimezone) {
// ...
});
I am missing out on some concept or logic.Can anyone please point me in the right direction?
CONTROLLER Example
Bad:
function MainCtrl () {
this.doSomething = function () {
};
}
angular
.module('app')
.controller('MainCtrl', MainCtrl);
Good:
function MainCtrl (SomeService) {
this.doSomething = SomeService.doSomething;
}
angular
.module('app')
.controller('MainCtrl', MainCtrl);
Factory Example
Bad:
function AnotherService () {
var someValue = '';
var someMethod = function () {
};
return {
someValue: someValue,
someMethod: someMethod
};
}
angular
.module('app')
.factory('AnotherService', AnotherService);
Good:
function AnotherService () {
var AnotherService = {};
AnotherService.someValue = '';
AnotherService.someMethod = function () {
};
return AnotherService;
}
angular
.module('app')
.factory('AnotherService', AnotherService);
For Detail Guidelines go through this blog :
Opinionated AngularJS styleguide for teams
Here is a working code example based on the assumption userTimezone and datetime are services which are apart of the localTimezone module.
The following has been modified
'data' which your factory is returning has been modified to return a string based on the factory pattern - as you were returning 'data' which referenced nothing
constructing the app has been moved to the top. This code should execute before anything else.
app variable removed - I don't like global variables.
Code:
angular.module('app', ['localTimezone']);
angular.module('localTimezone', []).factory('localTimezone',
function(userTimezone, datetime) {
var data = 'hello';
return { data: data } ;
});
angular.module('localTimezone').service('userTimezone', function() {
});
angular.module('localTimezone').service('datetime', function() {
});
angular.module('app').controller('tasksController',function ($scope,localTimezone) {
});
Codepen: http://codepen.io/anon/pen/wijmb (no errors appearing in console)
Take a look at http://angular-tips.com/blog/2013/08/understanding-service-types for information about the different service types in Angular.

Resources