Using $scope into a service

谁说我不能喝 提交于 2019-12-25 08:26:10

问题


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"
 }});

回答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.




回答2:


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




回答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>


来源:https://stackoverflow.com/questions/41284584/using-scope-into-a-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!