0

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.

Dwix
  • 1,139
  • 3
  • 20
  • 45

2 Answers2

2

The main point of assigning an object reference (Data service) to scope property is that it is shared between all scope properties that hold it.

What you're essentially doing here

app.controller("myFarmController", function($scope, $http, Data) {
$scope.Data = {"farm":{"idFarm":5}};
}

is assigning a new object to $scope.Data, it has nothing to do with original Data object. You should always stick to

$scope.Data = Data;
Data.farm = ...;
// or $scope.Data.farm = ...;

pattern to share the object between scopes.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • I understand now, thank you very much for your help, I wish I can mark this too as an answer. – Dwix Mar 01 '16 at 17:22
1

In myFarmController, you don't use the service in your code.

Try this:

app.controller("myFarmController", function($scope, $http, Data) {
  Data.farm.idFarm = 5;
  $scope.Data = Data;
}
etiennecrb
  • 597
  • 2
  • 10