Skip to content Skip to sidebar Skip to footer

How Pass Values Between Controllers With A Factory?

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(

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

Post a Comment for "How Pass Values Between Controllers With A Factory?"