1

I have a simple requirement in which I need to display the value of $scope.resAVal on my index.html page. I have $scope.resAVal available in the RootCtrl.

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
  <!--  required js libs and other stuff  -->
  </head>

  <body>
    <h3>{{resAVal}}</h3> <!-- This is what I need to display from RootCtrl -->
    <div ui-view></div>
  </body>

</html>

And here is the app.js:

var app = angular.module('plunker', ['ui.router']).

config(['$stateProvider', '$urlRouterProvider', '$locationProvider',
  function($stateProvider, $urlRouterProvider, $locationProvider) {

    $locationProvider.html5Mode(true);
    $urlRouterProvider.otherwise('/');
    $stateProvider
      .state('home', {
        url: '/',
        resolve:{
          resA:  function(){
            return {'value': 'A'};
          }
        },
        views: {

          '': {
            templateUrl: 'home.html',
            controller: 'RootCtrl'

          },

          'A@home': {
            templateUrl: 'a.html',
            controller: 'MainCtrl'
          },

          'B@home': {
            templateUrl: 'b.html',
            controller: 'MainCtrl'
          },
          'C@home': {
            templateUrl: 'c.html',
            controller: 'MainCtrl'
          }
        }

      });
  }
]);

app.controller('RootCtrl', function($scope, resA) {
  $scope.bar = [];
  $scope.resAVal = resA.value;

})
app.controller('MainCtrl', function($scope) {

  var fruits = [{"name": "Apple"}, {"name": "Banana"}, {"name": "Carrot"}];

  $scope.foo = 2;

  $scope.$watch('foo', function(value, oldValue) {
    $scope.bar.length = 0; //correct
    getBar(fruits, value);
  });

  function getBar(fruits, howManyFruits) {
    for (var i = 0; i < $scope.foo; i++) {
      $scope.bar.push(fruits[i]);
    }
  }

});

Here is the plunker for it.

Could somebody help me with it?

2 Answers 2

2

Any reason why you couldn't move the {{resAVal}} into the home.html view?

<h3>{{resAVal}}</h3>
<div class="row">
  <div ui-view="A"></div>
  <div ui-view="B"></div>
  <div ui-view="C"></div>
</div>

If you really can't do this, you can always inject the rootScope in your root controller:

app.controller('RootCtrl', function($scope, $rootScope, resA) {
  $scope.bar = [];
  $scope.resAVal = resA.value;
  $rootScope.resAVal = resA.value;
})
Sign up to request clarification or add additional context in comments.

Comments

1

Your problem is with $scope

If you declared $rootScope.resAVal it is working fine

Plunkr Here

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.