2015-02-10 181 views
1

我在AngularJS中使用工廠方法將名字和姓氏(前兩個控制器)的組合顯示爲全名(在第三個控制器中),但我沒有得到所需的輸出。這裏是我的代碼:AngularJS:在3個控制器之間共享數據

<html> 
 
<head> 
 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script> 
 
</head> 
 

 
<body> 
 
    <div ng-app="myApp"> 
 

 
\t \t <div ng-controller="FirstCtrl"> 
 
\t \t \t <input type="text" ng-model="Data.FirstName"> 
 
\t \t \t <br>FirstName is : <strong>{{Data.FirstName}}</strong> 
 
\t \t </div> 
 
\t \t <hr> 
 
\t \t <div ng-controller="SecondCtrl"> 
 
      <input type="text" ng-model="Data.LastName"> 
 
\t \t \t <br>LastName is : <strong>{{Data.LastName}}</strong> 
 
\t \t </div> 
 
     <div ng-controller="ThirdCtrl"> 
 
\t \t \t FullName is : {{Data.FirstName + " " + Data.LastName}} 
 
\t \t </div> 
 

 
\t </div> 
 
\t </div> 
 

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

 

 
     myApp.factory('Data', function() { 
 
      return { FirstName: '',LastName:'' }; 
 
     }); 
 

 
     myApp.controller('FirstCtrl', function ($scope, Data) { 
 
      $scope.Data = Data; 
 
     }); 
 

 
     myApp.controller('SecondCtrl', function ($scope, Data) { 
 
      $scope.Data = Data; 
 
     }); 
 
     myApp.controller('ThirdCrl', function ($scope, Data) { 
 
      $scope.Data = Data; 
 
     }); 
 
    </script> 
 
</body> 
 
</html>

能否請你幫助嗎?

+1

ThirdCtrl被拼錯 – 2015-02-10 06:46:11

回答

1

<html> 
 
<head> 
 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script> 
 
</head> 
 

 
<body> 
 
    <div ng-app="myApp"> 
 

 
\t \t <div ng-controller="FirstCtrl"> 
 
\t \t \t <input type="text" ng-model="Data.FirstName"> 
 
\t \t \t <br>FirstName is : <strong>{{Data.FirstName}}</strong> 
 
\t \t </div> 
 
\t \t <hr> 
 
\t \t <div ng-controller="SecondCtrl"> 
 
      <input type="text" ng-model="Data.LastName"> 
 
\t \t \t <br>LastName is : <strong>{{Data.LastName}}</strong> 
 
\t \t </div> 
 
     <div ng-controller="ThirdCtrl"> 
 
\t \t \t FullName is : {{Data.FirstName + " " + Data.LastName}} 
 
\t \t </div> 
 

 
\t </div> 
 
\t </div> 
 

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

 

 
     myApp.factory('Data', function() { 
 
      return { FirstName: '',LastName:'' }; 
 
     }); 
 

 
     myApp.controller('FirstCtrl', function ($scope, Data) { 
 
      $scope.Data = Data; 
 
     }); 
 

 
     myApp.controller('SecondCtrl', function ($scope, Data) { 
 
      $scope.Data = Data; 
 
     }); 
 
     myApp.controller('ThirdCtrl', function ($scope, Data) { 
 
      $scope.Data = Data; 
 
     }); 
 
    </script> 
 
</body> 
 
</html>

+0

謝謝:)得到它 – 2015-02-10 06:53:50

0

看來你拼寫錯誤的第三控制器名稱。

+0

謝謝:)當你得到錯誤,如'錯誤:[ng:areq]'時,得到它 – 2015-02-10 06:52:45

+0

,因爲你聲明的函數是未定義的。在上面的例子中,你聲明瞭名爲'ThirdCtrl'的控制器,但是你還沒有定義函數(因爲拼寫錯誤)。 – 2015-02-10 06:59:53

相關問題