RouteChangeStart事件在初始index.html页面加载时触发

RouteChangeStart event fired on initial index.html page load

本文关键字:加载 html 事件 index RouteChangeStart      更新时间:2023-09-26

路由更改事件在初始页面加载时触发,理想情况下,我希望在用户从初始页面转到下一个页面时触发,而不是在初始页面负载时。

在这里,我将指令"meeee"绑定到元素,并在该指令的链接函数中放入routeChangeStart的回调事件

在其中,当用户转到下一页时,我想用指令"meeee"触发回调以从当前页中删除元素。但是当前页面本身触发了"routeChangeStart"事件,在初始加载时删除了所有"meeee"元素,

请看这个plunkr代码http://plnkr.co/edit/h7nLME7YW7dI8qaBk1in?p=preview

Index.html

<!DOCTYPE html>
<html id="ng-app" ng-app="myApp">
  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script src=" https://code.jquery.com/jquery-1.11.2.min.js"></script>
    <script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.15/angular.js" data-semver="1.3.15"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-route.js"></script>
    <script src="app.js"></script>
  </head>
  <body>
            <div ng-controller="parentCtrl" class="">
                <div ng-view>
                </div>
            </div>
            <div id="d1-Me1" class="meeee">
                Meee1
            </div>
            <div id="d1-Me2" class="meeee">
                Meee2
            </div>
            <div id="d1-Me3" class="meeee">
                Meee3
            </div>
        </body>
</html>

App.js

var myApp = angular.module('myApp', ['ngRoute']);
myApp.controller('parentCtrl',['$scope','$window','$location',function ($scope,$window,$location) {

}]);
myApp.config(function($locationProvider,$routeProvider) {
    $routeProvider
    .when('/p1', {
      templateUrl:'page1.html',
    })
    .when('/p2', {
       templateUrl:'page2.html',
    })
    .when('/p3', {
      templateUrl:'partials/page3.html',
    })
    .when('/default', {
      templateUrl:'default.html',
    })
    .otherwise({
      redirectTo:'/default'
    });
});
myApp.directive("meeee",['$rootScope','$location', function ($rootScope, $location){
    return {
        restrict: 'C',
        link: function(scope, elm, attr) {
            $rootScope.$on('$routeChangeStart', function() {
                console.log('attr["id"]: '+attr["id"]);
                elm.remove();
            });
            elm.detach();
            angular.element("body").append(elm);
        }
    };
}]); 

default.html

<a href="#/p1">
    Page1
</a>
<br>
<br>
<a href="#/p2">
    Page2
</a>
<br>
<br>
<a href="#/p3">
    Page3
</a>

Page1.html

在第一页

<div id="p1-Me1" class="meeee">
    Page 1 Meee1
</div>
<div id="p1-Me2" class="meeee">
    Page 1 Meee2
</div>
<div id="p1-Me3" class="meeee">
    Page 1 Meee3
</div>

page2.html

<p>In Page Two</p>

page3.html

<p>In Page Three</p>

提前感谢您的帮助。

添加一个计数器,这样如果这是第一次页面加载,它就不适用了?