0

I have one html file and a controller assigned via $routeProvider

.when('/page/:pageId', {
            templateUrl: 'xxxx.html',
            controller: 'PageCtrl'
        })

and in the controller.js file i am accessing the value of pageId using $routeParams in 'PageCtrl' function.

  pageId = $routeParams.pageId;

and in view the html is

<div ng-controller="headerController">
  {{page.pageId}}
</div>

so in html i want to display the pageId, if pageId is passed in the url.

so here my question is once the pageId is passed its going correctly to the pageCtrl in Js and pageId scope value assigned, and am also able to assign the same scope value to the second controller 'headerController' by $controller('headerController', {$scope: $scope});

able to see that scope value is getting updated from one controller to another controller but my problem is that scope value which is updated, unable to view in html ({{page.pageId}})

ssilas777
  • 9,672
  • 4
  • 45
  • 68

1 Answers1

1

The problem is that your controller is getting instantiated twice: once from your $controller call and another time from the ng-controller directive in your view, each time with a difference scope, where the latter "wins" as far as what shows up in your view goes.

Consider this small demo:

JS

.controller('FirstController', function($scope, $controller){
   console.log('FirstController', $scope.$id); // logs 003
   $scope.pageId = '12345';
   $controller('SecondController', {$scope: $scope});
})
.controller('SecondController', function($scope){
    console.log('SecondController', $scope.$id); // logs 003 & 004
    $scope.scopeId = $scope.$id; // second scope "wins", appears in view
});

HTML

<div ng-controller="FirstController"></div>
<!-- {{scopeId}} outputs a value while {{pageId}} does not -->
<div ng-controller="SecondController">Scope: {{scopeId}} Page: {{pageId}}</div>

A better solution is to use a service to share data between controllers.

Community
  • 1
  • 1
Marc Kline
  • 9,399
  • 1
  • 33
  • 36