【问题标题】:Accessing scoped value from a Root Controller in AngularJS with UI Router使用 UI 路由器从 AngularJS 中的根控制器访问作用域值
【发布时间】:2015-06-21 16:39:48
【问题描述】:

我有一个简单的要求,我需要在我的index.html 页面上显示$scope.resAVal 的值。我在RootCtrl 中有$scope.resAVal

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'

          },

          '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 是它的笨蛋。

有人可以帮我吗?

【问题讨论】:

    标签: javascript html angularjs angular-ui-router angularjs-controller


    【解决方案1】:

    您无法将{{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;
    })
    

    【讨论】:

      【解决方案2】:

      你的问题在于 $scope

      如果你声明了$rootScope.resAVal 它工作正常

      Plunkr这里

      【讨论】:

        猜你喜欢
        • 2016-01-21
        • 1970-01-01
        • 2018-12-23
        • 2014-03-02
        • 1970-01-01
        • 2016-04-10
        • 2023-03-30
        • 1970-01-01
        • 2023-03-25
        相关资源
        最近更新 更多