简体   繁体   English

无法访问视图中的范围-Angular

[英]cannot access scope in views - Angular

For some reason I cannot retrieve the data from my controllers scope variables in my views. 由于某种原因,我无法从视图中的控制器作用域变量中检索数据。 All of my views use the same controller, so I am not sure what went wrong. 我所有的视图都使用相同的控制器,所以我不确定出了什么问题。 Any help would be appreciated. 任何帮助,将不胜感激。

Here is my App.js 这是我的App.js

    var app = angular.module('app', [
    'ngRoute'
    ]);


// Route configurations
app.config(['$routeProvider', function ($routeProvider){
$routeProvider.when('/', {
templateUrl: 'partials/home.html',
controller: 'MainController'
})
.when('/countries', {
templateUrl: 'partials/countriesList.html',
controller: 'MainController'
})
.when('/details', {
templateUrl: 'partials/countryDetails.html',
controller: 'MainController'
})
.otherwise({
 redirectTo: '/'
 });
}]);



// Main Controller Setup
app.controller('MainController', ['$scope', MainController]);
function MainController ($scope){
$scope.hello = 'hello';
}

Here is one of the view I am trying to access the scope in: 这是我尝试访问以下范围的视图之一:

<h1>Country List</h1>
<a href="#details"><button class="btn">Countries Details</button></a>

<p>hello: {{hello}}</p>

Here is my index.html 这是我的index.html

<!DOCTYPE html>
<html ng-app="app">
 <head>
  <title>Countries and Capitals</title>
  <link rel="stylesheet" type="text/css" href="css/vendor/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="css/main.css">
 </head>
 <body ng-controller="MainController" ng-cloak>
  <div class="container">
    <div class="row">
      <div class="col-sm-12 text-center">
        <ng-view></ng-view>
      </div>
     </div>
   </div>


  <script src="js/vendors.js"></script>
  <script src="js/scripts.js"></script>
 </body>
</html>

The problem because of nested scopes. 由于嵌套作用域而引起的问题。 The better way use some nested scopes is use controllerAs method. 使用某些嵌套作用域的更好方法是使用controllerAs方法。 Could you try: 您可以尝试:

``` ```

<body ng-controller="MainController as myctrl" ng-cloak>

<p>hello: {{myctrl.hello}}</p>  

``` ```

What you do while adding a controller in ng-route is you create another scope of the same controller. 在ng-route中添加控制器时,您要做的是创建同一控制器的另一个作用域。 My suggestion is you use either no controller ie remove controller attribute or add $parent. 我的建议是您不使用任何控制器,即删除控制器属性或添加$ parent。 in the view you are referencing. 在您引用的视图中。

The first one is preferred if u want to have same scope over a set of pages, the second one is preferred when u have different controllers for different pages. 如果要在一组页面上具有相同的作用域,则首选第一个;如果您要为不同的页面使用不同的控制器,则首选第二个。

Along with that if u want to access global variables, u can add them to $rootScope and access them globally.. 除此之外,如果您要访问全局变量,则可以将它们添加到$ rootScope并全局访问它们。

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM