Martin
Martin

Reputation: 24308

AngularJS: $scope NOT updating view from second controller

I wonder if anyone can help?

I have 1 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, its 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 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 ... Its like the $scope doesn't exist.

Does anyone know whats going on? I am using it correctly?

Thanks in advance

Upvotes: 1

Views: 2728

Answers (1)

Carlos Serrano
Carlos Serrano

Reputation: 111

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 = ...

If this doesn´t solve your problem, can you please provide a working fiddle with your problem. You can use this one as a starting point http://jsfiddle.net/IgorMinar/ADukg/

Upvotes: 3

Related Questions