0
路由更改事件是在初始頁面加載時觸發的,理想情況下,我想在用戶從初始頁面轉到下一頁而不是初始頁面加載時觸發。在初始index.html頁面加載時觸發RouteChangeStart事件
在這裏,我已經綁定了指令「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="[email protected]" 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>
預先感謝任何幫助。