1

In Angular JS instead of using the service in a module, can I create Javascript functions outside the controller and call it when I want to?

For example:

var UrlPath="http://www.w3schools.com//angular//customers.php"
//this will contain all your functions
 function testing_Model ($http){
 var self=this;

 self.getRecords=function(){
 $http({
  Method:'GET',
  URL: UrlPath,
 }).success(function(data){
  self.record=data.records;
});

}
self.getRecords();
}

angular.module("myApp", []);
app.controller('myController', function ($scope, $http) {
$scope.testing_Model = new testing_Model();}

When I run the code above, it says "$http is not a function".

Thanks in advance.

1 Answer 1

1

You need to pass $http to this function...

$scope.testing_Model = new testing_Model($http);

Although it will work it obviously goes against the idea of Angular. You must inject your function as a service in your controller to write testable code, track dependencies and just respect other developers who will be going to support your project later.

Sign up to request clarification or add additional context in comments.

1 Comment

yes, they definitely will, but please note that a service is a singleton, meanwhile your functions is a class-like. You can make this function e.g. be a part of service, e.g. you will need to call it like new myService. testing_Model(). The good thing is that $http service will be injected in your service only as long as you don't need it in your controller (some kind of encapsulation).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.