2017-10-18 123 views
0

我想通過(我認爲)兩個孩子控制器之間的數據。 試圖與工廠做到這一點。如何在工廠之間傳遞控制器之間的值?

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。兩個控制器都看到工廠(我可以在調試過程中看到這些功能)。我的問題是第二個沒有任何價值。就像它的一種全新的方法。不知道我錯過了什麼?

+0

無法保證'firstCtrl'在初始化'secondCtrl'時完全初始化,所以'firstCtrl'中設置的值可能不會被設置。最簡單的(儘管可能不是最好的方式)讓這些值同步是在'values.getValueA();' – laughingpine

+0

上使用'$ scope。$ watch'然而試圖在firstCtrl和secondCtrl中注入服務(從工廠返回)? – Andrea

回答

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="[email protected]" 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; 
    }); 
+0

我不懷疑這個作品。我的問題似乎是當我將它分割成不同的文件時,它會丟失。 first.html通過腳本標籤鏈接到工廠。 second.html也必須通過腳本標記鏈接到工廠。每個控制器似乎都將工廠初始化爲新的。 不知道如何調用工廠,所以它不會每次都被初始化。 –

相關問題