以下是我要链接到' Home'的index.html页面。和'关于'页。
<head>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="http://code.angularjs.org/1.2.13/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.min.js"></script>
<script src="index.js"></script>
<!--<script src="homecontroller.js"></script>-->
</head>
<body ng-app="routerApp" ng-controller="homeCntrl">
<nav class="navbar navbar-inverse" role="navigation">
<ul class="nav navbar-nav">
<li><a ui-sref="home">Home</a></li>
<li><a ui-sref="about">About</a></li>
</ul>
</nav>
<div class="container">
<div ui-view></div>
</div>
</body>
下面是index.js页面,其中我编写了显示错误消息的代码
var routerApp = angular.module('routerApp', ['ui.router']);
routerApp.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home.html'
})
.state('about', {
url: '/about',
templateUrl: 'about.html'
})
});
routerApp.controller('homeCntrl', function ($scope) {
$scope.form = {};
$scope.Save = function () {
alert('Save');
$scope.form.myForm.$setPristine();
}
});
routerApp.directive('confirmOnExit', function () {
return {
link: function ($scope, elem, attrs) {
window.onbeforeunload = function () {
if ($scope.form.myForm.$dirty) {
return "The form is dirty, do you want to stay on the page?";
}
}
$scope.$on('$locationChangeStart', function (event, next, current) {
if ($scope.form.myForm.$dirty) {
if (!confirm("The form is dirty, do you want to stay on the page?")) {
event.preventDefault();
}
}
});
}
};
});
以下是home.html页面
<form name="form.myForm" confirm-on-exit>
Name: <input name="input" ng-model="myModel.text">
<p>myModel.text = {{form.myModel.text}}</p>
<p>$pristine = {{form.myForm.$pristine}}</p>
<p>$dirty = {{form.myForm.$dirty}}</p>
<button type="submit" ng-click="Save()">Save</button>
</form>
现在我在输入字段中输入内容(页面变脏),然后点击&#39;关于&#39;标签。网址从主页更改为约,但它没有达到$ locationChangeStart。但是当我试图关闭broswer或点击后退按钮时它工作正常。但是每个人都说$ locationChangeStart是识别状态变化的方法,但对我来说它并没有在那里击中。如何获取有关状态更改的错误消息?
下面是plunker(注意:ui-sref在这里不起作用,但确切的代码在我的VS中正常工作。我无法弄清楚原因。但我的问题是当我在主页上更改链接从Home到About时页面是脏的然后它没有提示错误消息)