mardi 5 mai 2015

Fetching Angular Service Data

OBJECTIVE

Have Angular access a Service, retreive information, and display Service Information in two different controllers (later these controllers will manipulate this data, independently).

LIVE DEMO http://ift.tt/1IdTYSK

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();
}]);

QUESTIONS

  1. How can I check if the service is catching the original sentence?
  2. Why is it that both {{fetch1}} and {{fetch2}} aren't displaying properly?
  3. Is this a proper use of services interacting with controllers? Are there better ways?

Aucun commentaire:

Enregistrer un commentaire