由于某种原因,当我在资源 1 和资源 2 之间切换时,我的控制器被双重调用。
这是代码:
索引.html
<!DOCTYPE html>
<html ng-app="multiple_calls">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<a href="#res/1">1</a>
<a href="#res/2">2</a>
<div ng-view>
</div>
</body>
</html>
app.js
var app = angular.module('multiple_calls', []);
app.
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/res/:id', {templateUrl: 'res.html',
controller: 'res'
});
}]);
app.controller('MainCtrl', function($scope) {
});
app.controller('res', function($scope, $routeParams) {
console.log('resource called')
$scope.id = $routeParams.id;
});
res.html
{{id}}
http://plnkr.co/edit/HsCJmbllOcnlvlc1oiHa?p=preview
如果单击项目 1,然后单击项目 2,您将看到“资源调用”被打印 3 次:资源之间每次更改都会打印 2 次。
有任何线索为什么会发生这种情况吗?
发现一个完全相同的问题:
AngularJs:使用 $routeProvider 调用控制器两次
解决办法是在router url后面添加“/”:
- when('/res/:id',
+ when('/res/:id/',
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)