我有一個簡單的應用程序,我想共享一個可以由控制器設置的對象,然後從另一個控制器訪問它以完成任務,在這裏是代碼:控制器之間的共享對象不適用於AngularJS中的服務
的index.html
<body ng-app="myApp">
<ui-view></ui-view>
<!-- All js files included and working -->
<script type="text/javascript" src="angular/angular.min.js"></script>
<script type="text/javascript" src="angular/angular-ui-router.min.js"></script>
<script type="text/javascript" src="js/myApp.js"></script>
<script type="text/javascript" src="js/farms.js"></script>
</body>
app.js
var app = angular.module("myApp", ['ui.router']);
app.config(function config($stateProvider) {
$stateProvider.state("farm", {
url : "",
controller : "myFarmController as FarmCtrl",
templateUrl : "partials/farm.html"
})
$stateProvider.state("sau", {
url : "/sau",
controller : "mySauController as SauCtrl",
templateUrl : "partials/sau.html"
})
});
// Service used to share data
app.factory('Data', function(){
return { farm: {idFarm:''} };
});
app.controller("mySauController", function($scope, $http, Data) {
$scope.Data = Data;
}
farm.html
{{Data.farm}} <!-- this prints {"idFarm":5} -->
<div ui-sref="sau">GO TO SAU</div>
個
farms.js
app.controller("myFarmController", function($scope, $http, Data) {
$scope.Data = {"farm":{"idFarm":5}};
}
sau.html:
{{Data.farm}} <!-- this prints {"idFarm":""} -->
當我去farm.html,我看到物體顯示爲{"idFarm":5}
,但是當我點擊GO TO SAU
我定義,它會加載sau.html,但我得到一個空對象{"idFarm":""}
,因爲它在工廠中已定義,所以兩個控制器或兩個部分之間沒有數據傳遞,farm.html
& sau.html
。
非常感謝您的幫助。
它的工作,非常感謝! – dwix