I want to have common controller/service for dialogs,popover,modal and $ionicloading ,which will be used in all other state controller.how can I write the common controller?
You can write a factory and map all ionic service functions to own ones?
That’s it^^.
I have written a customised ionicPopup using factory.like below
var MyService=angular.module('MyService',['ionic']);
var utilService=MyService.service('utilService',function($rootScope,$ionicPopup)
{
return
{
showMessage:function (title,message)
{
var myPopup = $ionicPopup.show({
title: title,
subTitle: message,
scope: $scope,
});
myPopup.then(function(res) {
console.log('Tapped!', res);
});
};
}
});
And I have accessed the popup function in controller to show the popup.But it saying the showMessage() is undefined.
if you are mixin semantic of factories and services:
as service:
var MyService = angular.module('MyService',['ionic']);
var utilService = MyService.service('utilService',function($rootScope,$ionicPopup) {
this.showMessage = function (title,message) {
var myPopup = $ionicPopup.show({
title: title,
subTitle: message,
scope: $scope,
});
myPopup.then(function(res) {
console.log('Tapped!', res);
});
});
As factory you can use your approach but you have to use MyService.factory(…);
Thanks,I will try that using factory.
How do you use your factory in your controller?
I have tried both the way to call the showMessage() function.
.controller('MainCtrl', function($scope,$state,utilService) {
utilService.showMessage("Message");
//showMessage("Message");
});
i think your utilService is not loaded correctly.
try to console.log your utilService in your controller.
You could try to use following:
.controller('MainCtrl', ['$scope', '$state', 'utilService', function($scope, $state, utilService) {
console.log(utilService);
//showMessage("Message");
}]);
Maybe your way to create the service is wrong.
Because there is no need to store your module and srevice on a global variable.
angular.module('MyService',['ionic']).factory('utilService', .......).controller()
I am not sure the way i am doing is wrong or right way .I have separate js file for controller and services.I am not using single file.
I have printed the console.log(utilService). its throwing the utilService is undefined.
You can referrence an existing module:
// module definition
angular.module('myModule', ['ionic'])
// module reference
angular.module('myModule').factory(...);
also in different files i think.
Then you can include the files in the correct sortorder in your index.html
The problem is we should use return inside factory.I have added return in utilService ,now I can access the showMessage() function.
MyService.factory('utilService',function($rootScope,$ionicPopup){
return {
showMessage:function (title,message)
{
var myPopup = $ionicPopup.show({
title: title,
subTitle: message,
scope: $rootScope,
});
myPopup.then(function(res) {
console.log('Tapped!', res);
});
}
}
});