AngularJS:获取服务数据

时间:2015-05-05 23:43:03

标签: javascript angularjs angularjs-service

目的

让Angular访问服务,检索信息,并在两个不同的控制器中显示服务信息(稍后这些控制器将独立操作此数据)。

现场演示 http://plnkr.co/edit/pqnt5IHr3N3oUynfbz37?p=preview

的index.html

<html ng-app='plunker'>

<head>
  <title>AngularJS - Searching Text</title>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.1/angular.min.js"></script>
  <script src="app.js"></script>
</head>

<body>
  <h1>Search & Reverse Text</h1>

  <h2>Original Sentence sent to Service</h2>
  <form>
    <input type='text' ng-model='value' placeholder='insert sentence' />
    <button ng-click='setString(value)'>Set</button>
    <pre>Sentence: {{value}} </pre>
  </form>

  <div ng-controller='myController1'>
    <h2>Controller 1 fetching from Service</h2>
    <pre>{{fetch1}}</pre>
  </div>

  <div ng-controller='myController2'>
    <h2>Controller 2 fetching from Service</h2>
    <pre>{{fetch2}}</pre>
  </div>


</body>

</html>

app.js

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

/*Service to pass data between controllers */
app.service('passData', function() {
  $scope.stringValue = {};

  $scope.getString = function() {
    return stringValue;
  },

  $scope.setString = function(value) {
    stringValue = value;
  }
});

/* Controller1 catched string from  original sentence */
app.controller('myController1',['passData', function($scope) {
  $scope.fetch1 = passData.getString();
}]);

/*Controller2 catched string from  original sentence */
app.controller('myController2', ['passData', function(scope){
  $scope.fetch2 = passData.getString();
}]);

问题

  1. 如何检查服务是否正在捕捉原始句子?
  2. 为什么{{fetch1}}和{{fetch2}}都没有正确显示?
  3. 这是否正确使用与控制器交互的服务?还有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

在你的html中,你正在调用setString。如果你的意图是通过HTML调用服务方法,它就不会工作。您需要将服务注入控制器,通过控制器公开其方法,然后从HTML调用公开的方法。

其次,您没有向控制器注入$ scope。这是你在视图中获得{{fetch}}的方式

/* Controller1 catched string from  original sentence */
app.controller('myController1',['$scope', 'passData', function($scope, passData) {
  $scope.fetch1 = passData.getString();
}]);

/*Controller2 catched string from  original sentence */
app.controller('myController2', ['$scope','passData', function($scope, passData) {
  $scope.fetch2 = passData.getString();
}]);

但是您将服务注入控制器的方式是正确的

希望这有帮助