Thomas
Thomas

Reputation: 323

Open up content in another div with AngularJS

I have some content I wish to load into a div using Angular. For example:

<div class="number-and-description" ng-controller="thingDetails">                               
                                    <div class="number" ng-click="loadContent(thing.number, thing.description, thing.status)" ng-cloak>{{ thing.number }}</div>


                                    <p class="description" ng-click="loadContent(thing.number, thing.description, thing.status)" ng-cloak>{{ thing.description }}</p>
                                </div>  

I have another view outside of this div like this:

<!-- Main Content Area -->
            <section class="main-content group" ng-controller="thingDetails">                   
                <h1 ng-cloak>{{ thingNumber }}</h1>
                <div ng-cloak>{{ thingDescription }}</div>
                <div ng-cloak>{{ thingStatus }}</div>

            </section>

In my app.js file, I have this code:

thingApp.controller('thingDetails', ["$scope", function($scope) {

  $scope.loadContent = function(number, description, status) {

      $scope.thingNumber      = number;
      $scope.thingDescription = description;
      $scope.thingStatus      = status;




      return $scope;

  };



}]);

My question is, why doesn't the main content area div update when these values are changed? Right now it remains blank. thing.number, thing.description loads fine in the div I am clicking on - this data is coming from hardcoded JSON which appears fine. The issue is that when I click on the div, the OTHER main content div doesn't show/update the data. Could someone please help me out? Note that when I console.log(number) or console.log(description) etc. I can see the correct values, so they are being passed correctly to the loadContent() function.

Upvotes: 0

Views: 117

Answers (2)

charlietfl
charlietfl

Reputation: 171690

You have two separate instances of controller thingDetails , not one. They each have their own scope and do not share anything directly. A simple way to see this is put a console.log() in your controller and you will see it run each time the controller initializes

For controllers to share data you use a service and inject that service wherever it needs to be accessed.

Alternatively perhaps you don't need two instances and can wrap them in one scope in your view

Upvotes: 1

Dave M
Dave M

Reputation: 418

You are basically creating two controllers here with two different scopes. Thus, in the outer div, $scope.thingNumber, description, etc. are undefined as you are only changing the values on the inner scope.

A quick but messy fix to this problem would be to change your $scope's to $rootScopes. The proper way to do this though is via services/factories.

Upvotes: 0

Related Questions