2

i am learning angular and that is why some time i get stuck to understand the code. i got a code for custom service in angular. see the code first.

angular.module('yourModule').factory('alertService', function() {
    return {
        showError : function() {
            $.bigBox({
                title: title,
                content: content == null ? "An error occurred.<br /><br />If this error    persists, please contact support." : content,
                color: "#C46A69",
                //timeout: 6000,
                icon: "fa fa-warning shake animated",
                //number: "1",
                timeout: 3000
            });
        }
    };
});

Then you can inject it inside any controller and use it:

angular.module('yourModule').controller('yourController', function($scope, alertService) {
   someFunction().success(function (result) {
       // great!
   }).error(function (error) {
       // call standard error message function
       alertService.showError("Update Failed"); // use default error message
   });
});

question 1

when injecting inbuilt service then we use $ sign like this way $scope or $window etc but when injecting custom one then just write the service name without $ sign why?

if we need to inject my own service with $ sign then any problem would occur ? for $ sign do i need to create service with any specific code pattern ?

question 2

showError : function() {

}

can we declare the above function name like this way

this.showError = function() {

  };

$scope.showError = function() {

    }

please rectify me if there is problem in my understanding.

4 Answers 4

5

Question #1 $ sign is used for angular built in services, so that you can differentiate core and built in services. You are recommended not to use $ for your own services

Question # 2: NO. You are returning an object and showError is a key of the object and a function as a value . An object key is always defined as

{
   showError: function (){
   }
}

The following patterns are normally used with controllers, rather than services.

this.showError = function() {
};

$scope.showError = function() {
}
Sign up to request clarification or add additional context in comments.

Comments

3
  1. Because angular services have have a $ in their name, and your service doesn't. It's a convention that angular adopted to make sure thet the framework service names don't clash with your own service names. If you name your own services with a $, you ruin it. So, don't name your services with a leading $.

  2. No. A service can't be injected with a scope, since a service is global to the application, and not specific to a specific page. And using this.showError would bind the function to the factory, instead of binding it to the object (i.e. the service being defined) that is returned by the factory. You could use this.showError if you declared your service with the service() method rather than the factory() method. Read the documentation for a description of the various ways to define a service.

Comments

1

//creating the module ,controller and registering with the module all done in one line
//Use the method chaining mechnism as show below:
var myApp = angular.module('myModule', []).controller("myController",function($scope,stringService){
	console.log("Hi");
	$scope.transformString = function(input){
		
		console.log("Hello");
		$scope.output = stringService.processString(input);
	}

	
});

//Above is Controller file//
//below is custom service.You can put into separate file and reuse it another Controller //
myApp.factory('stringService',function(){
	 return {
	 	processString:function(input){
	 		if(!input){
				return input;
			}
			var output ="";
			for(var i = 0; i<input.length;i++){
				if(i > 0 && input[i] == input[i].toUpperCase()){
					output = output + " ";
				}
				output = output + input[i];
			}
			return output;

	 	}
	 }
});
table{
	border-collapse: collapse;
	font-family: Arial;
}
td{
	border: 1px solid black;
	padding: 5px;
}
th{
	border:1px solid black;
	padding: 5px;
	text-align: left;
}
<!DOCTYPE html>
<html>
<head>
	<title>Angularjs- Custom Services in Angular</title>
	<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
	<script type="text/javascript" src="script.js"></script>
	<script type="text/javascript" src="StringService.js"></script>
	<link rel="stylesheet" href="style.css">
</head>
<body >
<p> What is a services in an Angular Application?<br>
	Why do we need services in an angular application?
	<br>
	What are the benefits of using services?
  
</p>
<div ng-app="myModule">
	<div ng-controller="myController">
	
	
	<table border="1">
		
		<tbody>
			<tr>
				<td>Your String</td>
				<td><input type="text" ng-model="input" ></td>
			</tr>
			<tr>
				<td>Result</td>
				<td><input type="text" ng-model="output" ></td>
			</tr>
			<tr>
				<td></td>
				<td><input type="button" value="Process String" ng-click="transformString(input)" ></td>
			</tr>

		</tbody>
	</table>
	
</div>

</div>

</body>
</html>

3 Comments

Above is custom services example for String Transforming eg: Input as"PramodKharade". output:"Pramod Kharade"
What exactly does this service?
If you will give input like PramodKharadeSoftwareDeveloper. This string will transform like Pramod Kharade Software Developer
0

You can use the custom service simply given by AngularJs. Using Service:

var module = angular.module('myapp', []);

module.service('userService', function(){
    this.users = ['John', 'James', 'Jake'];
});

you can also use factory method.

module.factory('userService', function(){

    var fac = {};

    fac.users = ['John', 'James', 'Jake']; 

    return fac;

});

For reference: http://viralpatel.net/blogs/angularjs-service-factory-tutorial/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.