2014-06-23 147 views
1

我在關注在控制器之間共享數據的YouTube的tutorial。 由於某些原因,這兩個輸入不會返回共享數據(不可綁定)。任何人都可以讓我知道我的代碼中出了什麼問題嗎?Angularjs使用工廠在控制器之間共享數據

<!DOCTYPE html> 
    <html class="no-js"> 
    <head> 
     <meta charset="utf-8"> 
     <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
     <title></title> 
     <meta name="description" content=""> 
     <meta name="viewport" content="width=device-width"> 
     <link rel="stylesheet" href="/css/app.css?2"> 
     <script src="/bower-foundation/js/vendor/modernizr.js"></script> 
     <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js?2"></script> 
     <!-- angularjs --> 
     <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script> 
     <script> 
      var myApp = angular.module('myApp', []); 

      myApp.factory('Data', function(){ 
       return {msg:"I am data from a service"} 
      }) 

      function firstctrl($scope, Data) { 
       $scope.data = Data; 
      } 
      function secondctrl($scope, Data) { 
       $scope.data = Data; 
      } 
     </script> 
    </head> 
    <body ng-app="myApp"> 


     <div ng-controller="firstctrl"> 
      <input type="text" ng-model="data.msg"> 
      <h1>{{data.msg}}</h1> 
     </div> 


     <div ng-controller="secondctrl"> 
      <input type="text" ng-model="data.msg"> 
      <h1>{{data.msg}}</h1> 
     </div> 


    <!-- javascript --> 
     <script src="/bower-foundation/js/foundation.min.js?3"></script> 
     <script src="//cdnjs.cloudflare.com/ajax/libs/fastclick/0.6.11/fastclick.min.js?2"></script> 
     <script src="/js/min/app.min.js?3"></script> 
    </body> 
    </html> 
+0

它的做工精細看看我的回答 –

+1

什麼不工作?代碼很好:http://plnkr.co/edit/N2576p6ShTEnyxC8yPx8?p=preview – pixelbits

回答

1

它的做工精細,看看這個

Working Demo

HTML

<div ng-app='myApp'> 
    <div ng-controller="firstctrl"> 
     <input type="text" ng-model="data.msg" /> 
     <h1>{{data.msg}}</h1> 

    </div> 
    <div ng-controller="secondctrl"> 
     <input type="text" ng-model="data.msg" /> 
     <h1>{{data.msg}}</h1> 

    </div> 
</div> 

SCRIPT

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

myApp.factory('Data', function() { 
    return { 
     msg: "I am data from a service" 
    }; 
}) 

function firstctrl($scope, Data) { 
    $scope.data = Data; 
} 

function secondctrl($scope, Data) { 
    $scope.data = Data; 
} 

也看看這個東西

AngularJS - Sharing variables between controllers

+0

奇怪的是,當我更新輸入時,不會返回數據。編譯後h1只顯示{{data.msg}}。 – user2734550

+0

不要看到數據值打印在文本字段,如h1 ....並且每當你改變它的值反映在所有區域右 –

+0

正確,這就是我的問題 – user2734550

相關問題