如何在控制器与工厂之间传递值?

时间:2017-10-18 18:40:10

标签: javascript angularjs angularjs-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;
        }
    };
}]);

在不同的JS文件中有如此不同的控制器。 controller1.js(这个设置值)

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

       values.setValueA("MyTestValue");

}]);

controller2.js读取值。

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

        $scope.valueA = values.getValueA();   

}]);

我在HTML端包含了js。两个控制器都看到工厂(我可以在调试期间看到这些功能)。我的问题是第二个没有任何价值观。就像它的全新方法一样。不确定我错过了什么?

1 个答案:

答案 0 :(得分:0)

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