[英]Angularjs: Controller is called multiple times
出於某種原因,當我在資源1和資源2之間切換時,我的控制器被雙重調用。
這是代碼:
的index.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調用控制器兩次
解決方案是在路由器URL的末尾添加“/”:
- when('/res/:id',
+ when('/res/:id/',
如果您更改為角度版本1.1.5,這也適用
當我編寫指令並包含控制器時,我仍在學習角度,我遇到了這個問題。
我希望能幫助別人,因為我花了很長時間才看到我做了什么:
.directive("list", function() {
return {
restrict: "E",
transclude: true,
replace: false,
templateUrl: "contacts/list",
controller: "CMSController", //- not needed at all
controllerAs: 'cCtrl'//- not needed at all
};
})
function config($routeProvider, $locationProvider, $httpProvider) {
$routeProvider
....
.when('/CMS', {
templateUrl: 'contacts/index',
controller: 'CMSController',
controllerAs: 'cCtrl',
access: {restricted: true}
})
....
另一個對我app.directive
解決方案是,如果您定義了一個指令,請不要將其控制器設置為多次調用的控制器,只需使用app.directive
將指令添加到您的應用程序app.directive
。
app.directive('myDirective',[ '$window', function ($window) {
function link(scope, element) {
// stuff
});
};
return {
restrict: 'A',
scope: {offset: "@"},
link: link,
// controller: myCtrl //myCtrl was called multiple I comment this line
};
}]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.