1

I started learning angularjs in w3schools tutorials. Below was an example that was given to write your custom services

app.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});


app.controller('myCtrl', function($scope, hexafy) {
    $scope.hex = hexafy.myFunc(255);
});

Why doesn't the below work -

app.service('hexafy', function(x) {
        return x.toString(16);
});
app.controller('myCtrl', function($scope, hexafy) {
  $scope.hex = hexafy(255);
});

Here I am letting the function accept an argument and processing it without creating a new function within it. But this approach doesn't seem to work.

2
  • That's just the way AnglarJS works. Using .service(), you must pass a function that will be used to instantiate a new object. Here, that's not what you do, therefore, it does not work. BTW, w3schools is quite a weird place to start with AngularJS, you will probably find some better tutorials on the official website. Commented Mar 14, 2018 at 14:37
  • Thanks for the answer , @sjahan! Commented Mar 14, 2018 at 14:49

2 Answers 2

4

Service is supposed to be instantiatable function, so Angular creates instance of the service for you, like a constructor function. If you just want to register a function to call without constructing an instance use value:

app.value('hexafy', function(x) {
  return x.toString(16);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot @dfsq
what is an instantiable function? Why is function(x) that I had given in my post not instantiable?
I mean constructor functions. Then you use function as a constructor it returns an instance object. If you use service, Angular will expect function you provide to return an object which will be used as service instance. When you write service('xxx', function (x) { return x.toString(16) }) result of such construction will not be a function, it will an empty object. That's why it doesn't work.
1

You need a method are a value to access the service class, It is better to keep a method for your need, I believe below is the code which is required for your need.

app.service('hexafy', function() {
        this.toString = function(x){
        return x.toString(16);
        }
});
app.controller('myCtrl', function($scope, hexafy) {
  $scope.hex = hexafy.toString(255);
});

or you can access it as the value just like the above answer.

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.