简体   繁体   中英

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

    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

<!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. 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. My suggestion is you use either no controller ie remove controller attribute or add $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..

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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