I have a simple app, and I want to share an object which can be set by a controller, and then access it from another controller to complete a task, here is the code :
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":""} -->
When I go to farm.html, I see that object shows as {"idFarm":5}
, But when I click on GO TO SAU
that I defined, it loads the sau.html, but I get an empty object {"idFarm":""}
, as it was defined in the factory, so no data passed between the two controllers or the two partials, farm.html
& sau.html
.
Thank you in advance for your help.