angularjsangularjs-scopeangularjs-ng-repeat

AngularJS: $scope not updating view from second controller


I have an HTML file and a controller assigned via the $routeProvider like so

          .when('/', {
            templateUrl: 'views/contents.html',
            controller: 'FirstCtrl'

Everything was working fine, I had my view do a ng-repeat over a object and the view updated like so

   <tbody ng-repeat="item in contents.data">
     <tr>        

This code was working fine, I updated my item via the FirstCtrl like so

   $scope.contents = {};
   $scope.contents.data = {...}

I have extracted this functionality out into its own controller, it's still the same view, so I have 1 view and 2 controllers... The second controller is used by specifying ng-controller on the tbody like so

   <tbody ng-controller="SecondCtrl" ng-repeat="item in contents.data">
     <tr>

Now I know the controller is working as I have insert an ng-click on a <tr> and it fires the the function. I am also updating my $scope from my second controller but it seems to be also blank.

From the documentation it states that if the $scope exists in the parent controller (first) then the child controller overwrites it (second) but this is not my case, I don't have it defined in the first controller any more.

I even tried a simple test of

    $scope.testme = "hi";

and the view

    {{ testme }}

and nothing ... it's like the $scope doesn't exist.

What's going on?


Solution

  • If you are initializing the $scope.contents inside of the SecondCtrl then you are probably experimenting some $scope shadowing.

    Try creating the "contents" object inside of the FirstCtrl and when you update the data. Do not recreate the contents object (i.e. don't do >> $scope.contents = {};) just update the data object/array >> $scope.content.data = ...