如何使用控制器访问服务内的变量

时间:2017-02-28 18:29:21

标签: angularjs angular-services angular-controller

我有两个html屏幕,在第一个屏幕中我得到一个输入并将其保存在服务中,以便另一个控制器访问相同的值并在第二个屏幕中显示该值。这里我能够将第一个html屏幕的值存储到服务中,但是在使用另一个控制器访问该值时会遇到问题。那么如何从另一个控制器访问服务中的值以及这里的错误是什么。

服务:

var app = angular.module('myApp', []);
app.service('variableProperties', function() {
this.sampleVariable= function(data){
    var dataStored= 'data';
return {
    getString: function() {
        return dataStored;
    }}}});

控制器1:

app.controller('controller1',function($scope, variableProperties){
  $scope.submit= function(formData){
     variableProperties.sampleVariable($scope.name);
     $state.go('screen2.html');
   }
   })

控制器2:

app.controller('controller2',function($scope, variableProperties){
        $scope.getData = variableProperties.getString();
})

2 个答案:

答案 0 :(得分:0)

它是您的服务,代码根本没有多大意义。

这是一个服务,它返回一个带有清除getter和setter以及数据存储的新实例。

app.service('variableProperties', function() {
    var newService = {};
    newService.data = ""; // (optional) initialize the storage variable to some empty string

    // define a setter
    newService.sampleVariable = function(data){
      newService.data = data;
    }
    // define a getter
    newService.getString = function() {
      return newService.data;
    }

    // return the newly defined service
    return newService;
});

答案 1 :(得分:0)

问题在于您的服务,请按以下方式更改

app.service('variableProperties', function() {
  var dataStored;
  var sampleVariable = function(data) {
    dataStored = data;
  }
  var getString = function() {
    return dataStored;
  }
  return {
    sampleVariable: sampleVariable,
    getString: getString
  };
});

<强>样本

var app = angular.module('myApp', []);

app.controller('Controller1', function($scope, variableProperties) {
  $scope.someData = "i am from controoler 1";
  variableProperties.sampleVariable($scope.someData);
});
app.controller('Controller2', function($scope, variableProperties) {
  $scope.lists = variableProperties.getString();
});
app.service('variableProperties', function() {
  var dataStored;
  var sampleVariable = function(data) {
    dataStored = data;
  }
  var getString = function() {
    return dataStored;
  }
  return {
    sampleVariable: sampleVariable,
    getString: getString
  };
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title></title>
</head>
<body ng-app="myApp">     
        <div ng-controller="Controller1">
    <ul>
      controller 1
    </ul>
  </div>
  <div ng-controller="Controller2">
    <ul>
      <li>
        controllert 2 section {{lists}}
      </li>
    </ul>
  </div>
  <script type=" text/javascript " src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular.js "></script>
  <script type="text/javascript " src="MainViewController.js "></script>
</body>
</html>