user4234560
user4234560

Reputation: 3

AngularJS : Error on Multiple Controller

I'm learning AngularJS. I tried with sample code, got error when I ran it. It's basic example I guess so. Wasn't sure of the error.

On FireFox when I tried with FireBug, it show MyController1 not a function.

Any help appreciated.

<!DOCTYPE html>
<html lang="en">

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>

<body ng-app="myapp">

<div ng-controller="MyController1">
    <div ng-click="myData1.doClick()">Click here</div>
</div>

<script>
    angular.module("myapp", [])
            .controller("MyController1", function($scope) {
                $scope.myData1 = {};
                $scope.myData1.doClick = function() {
                    alert("clicked");
                }
            } );
</script>


<div ng-controller="MyController2" >
    <div ng-click="myData.doClick($event)">Click here for Event Coordinates</div>
</div>

<script>
    angular.module("myapp", [])
            .controller("MyController2", function($scope) {
                $scope.myData = {};
                $scope.myData.doClick = function(event) {
                    alert("clicked: " + event.clientX + ", " + event.clientY);
                }
            } );
</script>   

</body>
</html>

Upvotes: 0

Views: 240

Answers (1)

Yogesh Khatri
Yogesh Khatri

Reputation: 1210

When you doing anuglar.module again, you should not use [] as second parameter. Using second parameter will reinitialize the module, and if second parameter is not passed, the same module is used.

So the code should be like this in your second script tag

angular.module("myapp")
        .controller("MyController2", function($scope) {
            $scope.myData = {};
            $scope.myData.doClick = function(event) {
                alert("clicked: " + event.clientX + ", " + event.clientY);
            }
        } );

Upvotes: 4

Related Questions