Skip to content Skip to sidebar Skip to footer

Using $scope Into A Service

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(

Solution 1:

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()

Solution 2:

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.

Solution 3:

$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>

Post a Comment for "Using $scope Into A Service"