简体   繁体   English

AngularJS-路线变更的更新控制器

[英]AngularJS - Update Controller on Route Change

Setup 设定

 app.controller('headerController', ['$scope', '$routeParams', function($scope, $routeParams) {
     $scope.data = $routeParams;
 }]);

 app.config(['$routeProvider',
     function ($routeProvider) {
         $routeProvider.
             when('/:url', {
                 template: '<h2>Hello World</h2>'
             })
 }]);

Layout 布局

<body>
    <div ng-controller="headerController">
      Current Url:{{data.url}}
    </div>

    <div ng-view></div>

    <ul>
       <li>
          <a href="#/pageA">Page A</a>
       </li>
       <li>
         <a href="#/pageB>Page B</a>
     </li>
</body>

Problem 问题

I want the header section to constantly update with the current url everytime the route changes. 我希望标题部分在每次路由更改时都使用当前URL不断更新。 When I load my app for the first time, this works. 当我第一次加载我的应用程序时,此方法有效。 However, if I change the route, the controller does not update to the new url. 但是,如果更改路由,则控制器不会更新为新的URL。

My question is not about solving this exact problem because I know there are other ways to do it, but rather solving it using this setup. 我的问题不是解决这个确切的问题,因为我知道还有其他方法可以解决此问题,而是使用此设置来解决。 In other words, I need to know how to provide a controller outside of a view with my current route, and have that controller update every time the route is changed. 换句话说,我需要知道如何在视图之外为我的当前路线提供控制器,并在每次更改路线时使该控制器更新。

You should try to make $scope.data a function to have it reevaluate. 您应该尝试使$ scope.data为函数来重新评估它。

Otherwise I suggest you listen to onRouteChangeSuccess to watch the URL change. 否则,建议您听onRouteChangeSuccess观看URL更改。

I tried your code and with some slight changes such as in the following, it is perfectly working on my side with firefox. 我尝试了您的代码,并进行了一些细微的更改,例如以下内容,它在使用firefox时非常适合我。 The url correctly updates to Page A or Page B on change 更改后,URL正确更新为页面A或页面B

I also may have not understood the question? 我可能还不明白这个问题?

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

app.controller('headerController', ['$scope', '$routeParams', function($scope, $routeParams) {
     $scope.data = $routeParams;
 }]);

 app.config(['$routeProvider',
     function ($routeProvider) {
         $routeProvider.
         when('/:url', {
             template: '<h2>Hello World</h2>'
         })
 }]);



<html ng-app="app">
<head> 
    <script src="angular.min.js"></script>
    <script src="angular-route.js"></script>
    <script src="controller.js"></script>
</head>
<body>
    <div ng-controller="headerController">
      Current Url:{{data.url}}
    </div>

    <div ng-view></div>

    <ul>
       <li>
          <a href="#/pageA">Page A</a>
       </li>
       <li>
          <a href="#/pageB">Page B</a>
       </li>
</body>

Cheers 干杯

Nicolas 萨科

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

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