How pass values between controllers with a factory

2019-08-22 16:40发布

问题:

I'm trying to pass data between (I think) two child controllers. Trying to do this with a factory.

testFactory.js

          app= angular.module('testApp');
          app.factory('values', [function () {

    var testValues= {
        valueA: ''
    };

    return {
        setValueA: function(a) {
            testValues.valueA= a;
        },
        getValueA: function() {
            return testValues.valueA;
        }
    };
}]);

In different JS files so different controllers. controller1.js (this one sets the value)

angular.module('testApp')
    .controller('firstCtrl', ['$scope''values',
        function ( $scope, values) {

       values.setValueA("MyTestValue");

}]);

controller2.js this reads the value.

angular.module('testApp')
    .controller('secondCtrl', [ '$scope', 'values',
        function ( $scope, values) {

        $scope.valueA = values.getValueA();   

}]);

I include the js on the HTML side. Both controllers see the factory (I can see the functions during debugging). My problem is the second one doesn't have any values. Like its a brand new method. Not sure what I'm missing?

回答1:

The code Looks fine. I made a sample to replicate the same. working code is below



<!DOCTYPE html>
<html ng-app="myapp">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
    <script src="app.js"></script>
  </head>

  <body >
    <div>
      <h1>Services</h1>
      <div ng-controller="secondCtrl as list">
         <p ng-repeat="value in list.values">{{ value.valueA }}</p>
      </div>

      <div ng-controller="firstCtrl as post">
        <form ng-submit="post.addValue(post.newValue)">
          <input type="text" ng-model="post.newValue">
          <button type="submit">Add Message</button>
        </form>
      </div>
    </div>
  </body>
</html>




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

    app.factory('values', function(){

      var values = {};
      values.list = [];
      values.list.push({valueA: 'hellomessage'});
      values.add = function(message){
           values.list.push({valueA: message});
        };

      return values;
    });

    app.controller('firstCtrl', function (values){
      var self = this;
      self.newValue = 'First Value';
      self.addValue = function(value){

        values.add(value);
        self.newValue = '';
      };

    });

    app.controller('secondCtrl', function (values){
      var self = this;

      self.values = values.list;
    });