将$ scope用于服务

sam*_*sam 0 javascript angularjs ionic-framework

我对以下代码的期望是它会绑定$ scope.as.但没有任何显示,控制台中没有显示错误

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"
 }});
Run Code Online (Sandbox Code Playgroud)

Sat*_*pal 5

您无需$scope在服务中使用.您可以简单地return从服务中获取数据并绑定到$scope控制器中的变量

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

您应该阅读将$ scope注入角度服务函数()