Angular: Service to Pass Data To Another Controlel

2019-09-02 06:48发布

问题:

So, I have a ng-repeated list of items as such.

<li><a ng-click="{{person.id}}">Name of Person</a></li>

I would like to create a service wherein, on click, I can collect that person.id and pass it to another controller in a different route.

This would normally be very simple by just using the url and route params, however, in this case it is important that the person.id not be exposed within the browser url.

-- More Context

Whether service or not, I am needing to extract a {{person.Id}} that is data available via an ng-repeat on a list page of persons.

On click, I move from a persons controller to a new route with a "person" controller. I need that "person" controller to be able to pull the {{Person.ID}} that was clicked on the previous route in order to look up that person in a DB.

Any help would be really great!

回答1:

Services aren't meant to interact directly with DOM elements. DOM should interact with directives/controllers. Controller should interact with models.

This example below demonstrates sending data from controller 1 to myFactory and then controller 2 gets it the value from myFactory.

  angular
    .module('app', [])
    .factory('myFactory', myFactory)
    .controller('myCtrl1', myCtrl1)
    .controller('myCtrl2', myCtrl2);

  function myFactory() {
    var fromSender = null;
    return {
      setSender: function(sender) {
        fromSender = sender;
      },
      getSender: function() {
        return fromSender;
      }
    };
  }

  function myCtrl1(myFactory) {
    var vm = this;
    vm.setSender = myFactory.setSender;
  }

  function myCtrl2(myFactory) {
    var vm = this;
    vm.getSender = myFactory.getSender;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>

<div ng-app="app">
  <div ng-controller="myCtrl1 as ctrl1">
    Controller 1: <br>
    <button ng-click="ctrl1.setSender('from controller 1')">Send to myFactory</button>
  </div>
  <hr>
  <div ng-controller="myCtrl2 as ctrl2">
    Controller 2: <br>
    value from ctrl1 via myFactory:  {{ctrl2.getSender()}}
  </div>
</div>



回答2:

All services in Angular are singletons. So if you inject personService or something like that, in multiple controllers, then those controllers will be using the exact same object. So if you set a value on that service, then the other controllers will be able to see it.

With more code and context, I'll be able to give a more specific example.