0

What I expect from below code is it would bind $scope.as . But nothing is displaying and no error is shown in console

var testModule = angular.module('testmodule', [])
.controller('ctrl', function ($scope, mser) {
  mser.aa();
 })
.service('mser', function($scope /* Would $scope be here */) {
  this.aa = function(){
  $scope.as = "hello mars"
 }});
sam
  • 688
  • 1
  • 12
  • 35
  • 1
    Why you want to use `$scope` in service? – Satpal Dec 22 '16 at 13:45
  • @Satpal bro i m learning angular and stuck at this point – sam Dec 22 '16 at 13:46
  • @sam Really bad idea to use scope in service. Adding scope to your service increases angular watchers with every single instance you call from controller, making app slow (more than 2000 watchers : angular gets slower and is visible on browser) . Service is no longer needed at this point because, just add another function/ move service logic in controller. As long as you are playing with angular - sky is the limit, have a ball. – Sudhindra_Chausalkar Dec 22 '16 at 14:07

3 Answers3

5

You don't need to use $scope in service. You can simply return data from service and bind to $scope variable in controller

var testModule = angular.module('testmodule', [])
.controller('ctrl', function ($scope, mser) {
    $scope.as = mser.aa();
 }).service('mser', function() {
    this.aa = function(){
        return "hello mars"
    }   
}); 

You should read Injecting $scope into an angular service function()

Community
  • 1
  • 1
Satpal
  • 132,252
  • 13
  • 159
  • 168
1

you can't use $scope in service you should use it in your controller it is used to glue controller and DOM. Since services are injected in controllers so there is no individual existence of a service.

Vikash Kumar
  • 1,712
  • 1
  • 11
  • 17
0

$scope object is basically used to glue together the view and the controller of your angular application. It does not make much sense to pass it into a service. Services are singleton objects used to share data among several controllers,directives,filters etc.

Some changes need to be made in your code :

1. Instead of using $scope in service used it in controller.

2. Return the object from the service and get it into the controller inside a $scope object.

Based on the approach described above, you can change your code like this :

controller :

var testModule = angular.module('testmodule', [])
.controller('ctrl', function ($scope, mser) {
  $scope.as = mser.aa();
})
.service('mser', function() {
  this.aa = function(){
    return "hello mars";
}});

view :

<span>{{::as}}</span>
Debug Diva
  • 26,058
  • 13
  • 70
  • 123