$ scope。$ on('$ viewContentLoaded',..调用两次以上

时间:2016-06-08 03:33:20

标签: javascript angularjs javascript-events

例如,我有这么简单的片段:

var sampleApp = angular.module('sampleApp', []);
sampleApp.config(['$routeProvider',
  function($routeProvider, $rootScope) {
    $routeProvider.
      when('/AddNewOrder', {
    templateUrl: 'add_order.html',
    controller: 'AddOrderController'
      }).
      when('/ShowOrders', {
    templateUrl: 'show_orders.html',
    controller: 'ShowOrdersController'
      }).
      otherwise({
    redirectTo: '/AddNewOrder'
      });
}]);

sampleApp.controller('AddOrderController', function($scope, $rootScope) {
    $scope.message = 'This is Add new order screen';

    $scope.$on('$viewContentLoaded', function (event, toState, toParams, fromState, fromParams) {
        console.log("Add new order");
    });

});

sampleApp.controller('ShowOrdersController', function($scope,$rootScope) {
    $scope.message = 'This is Show orders screen';

    $scope.$on('$viewContentLoaded', function (event, toState, toParams, fromState, fromParams) {
        console.log("Show orders");
    });
});

它是来自ng示例的app.js,在浏览器中它的示例看起来如此: enter image description here

您可以在此处看到完整版:http://plnkr.co/edit/jc3nFBAaBLMiGMYV4TZW?p=preview

哪里有些奇怪:

$scope.$on('$viewContentLoaded', function (event, toState, toParams, fromState, fromParams) {
        console.log("Add new order");

$scope.$on('$viewContentLoaded', function (event, toState, toParams, fromState, fromParams) {
            console.log("Show orders");
        });

每次点击链接时都会调用两次。 我也尝试使用'$ routeChangeSuccess',但结果相同。 为什么会这样? 需要做些什么才能获得$ scope的调用。$ on(..)?

1 个答案:

答案 0 :(得分:2)

将您的href="#AddNewOrder"更改为href="#/AddNewOrder"。 因为你的控制器初始化了两次。