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}})

1
  • can you provide an example of what you expect to happen, and what is actually happening? Commented Jun 9, 2014 at 6:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.