2013-10-04 99 views
6

出於某種原因,當我在資源1和資源2之間切換時,我的控制器被雙重調用。Angularjs:控制器被多次調用

下面的代碼:

的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次資源之間的每一個變化。

任何線索爲什麼發生這種情況?

回答

1

,如果你改變角度的版本這也適用1.1.5

0

我仍然在學習角度,當我編寫指令幷包含控制器時,我遇到了這個問題。

我希望能幫助別人,因爲我花了相當長的一段時間,看看我做了什麼:

.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} 
    }) 
    ....