1

我有一个简单的要求,我需要在我的index.html页面上显示$scope.resAVal的值。我在RootCtrl中有$scope.resAVal使用UI路由器从AngularJS的根控制器访问范围值

的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> 

这里是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' 

      }, 

      '[email protected]': { 
      templateUrl: 'a.html', 
      controller: 'MainCtrl' 
      }, 

      '[email protected]': { 
      templateUrl: 'b.html', 
      controller: 'MainCtrl' 
      }, 
      '[email protected]': { 
      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是它的plunker。

有人可以帮我吗?

回答

1

你的问题是与$范围

如果你宣布$rootScope.resAVal是正常工作

Plunkr Here

2

你为什么不能将{{resAVal}}移动到home.html视图中的任何原因?

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

如果你真的不能做到这一点,你可以随时注入rootScope在你的根控制器:

app.controller('RootCtrl', function($scope, $rootScope, resA) { 
    $scope.bar = []; 
    $scope.resAVal = resA.value; 
    $rootScope.resAVal = resA.value; 
}) 
相关问题