AngularJS $ routeParams:设置$ scope变量

时间:2018-11-02 09:44:02

标签: angularjs angular-router

使用AngularJS 1.6.1,我的页面只有一个控制器。我想使用$ routeParams将$ scope变量设置为(可选)路由参数的值。但不幸的是,这根本不起作用:

var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider) {
   $routeProvider
      .when('/', {
         templateUrl: '/partials/partial1.htm'
      })
      .when('/:artist/:album', {
         templateUrl: '/partials/partial1.htm'
      })
      .otherwise({
         redirectTo: '/'
      });
});

myApp.controller('myController', function($scope, $routeParams) {
   $scope.artist = $routeParams.artist;
   $scope.album = $routeParams.album;
});

使用console.log时,我可以看到正在设置值...但是看来路由器正在为参数化路由启动一个单独的控制器。因此,我尝试了使用其他控制器,然后使用$ emit和$ on将消息从第二个传递到第一个控制器。

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

myApp.config(function($routeProvider) {
   $routeProvider
      .when('/', {
         templateUrl: '/partials/partial1.htm'
      })
      .when('/:artist/:album', {
         templateUrl: '/partials/partial1.htm',
         controller: 'URLController'
      })
      .otherwise({
         redirectTo: '/'
      });
});

myApp.controller('URLController', function($scope, $routeParams) {
   $scope.$emit('UrlChanged', $routeParams.artist, $routeParams.album);
});

myApp.controller('myController', function($scope, $routeParams, $http) {
   $scope.$on('UrlChanged', function(event, artist, album) {
      $scope.artist = $routeParams.artist;
      $scope.album = $routeParams.album;
      // CORRECTION: It keeps firing events if I add this
      $scope.loadAlbum();
      // loadAlbum() contains a call to a Rest API on the same server via $http.get.
      // Obviously this triggers the creation of a new URLController????
   });
});

但这只会无限期地触发UrlChanged个事件。

更正:如果我添加一个$http.get呼叫,它只会 不断触发

要实现我的目标我该怎么做?

1 个答案:

答案 0 :(得分:1)

尝试收听$route服务的$routeChangeSuccess事件(因为MainController似乎在实际事件/导航发生之前已初始化):

myApp.controller('MainController', ['$scope', function ($scope) {
    $scope.$on('$routeChangeStart', function ($event, next, current) {
        var params = next.params;
        if (params) {
            $scope.artist = params.artist;
            $scope.album = params.album;
        }
    });
}])