user2656127
user2656127

Reputation: 665

Can't initialise a controller in AngularJS

So I'm trying to get started with Angular, but running into a very simple issue. I have 3 pages in my application (index.html, app.js and invite.js). Now, I seem to have successfully initialised the angular application and I can run the application (see the console.log in app.js).

The problem is - I'm trying to create another controller, and I'm testing it with a simple alert() function - but I'm not getting any response.

Could anyone help point out where I'm going wrong? I assume it's a simple issue!

Thanks in advance :)

Index.html

<!doctype html>
<html lang="en">
<head ng-app="batchSparta">
    <meta charset="UTF-8">
    <title>Batch Inviter</title>
    <!-- CSS and Javascripts --> 
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
    <script src="app.js"></script>
    <script src="invite.js"></script>
    <!-- END CSS and Javascripts -->

</head>
<body>
    <div class="container" ng-controller="InviteController">
        <div class="well">
            Here you can bulk-invite users to your Sparta account.
        </div>  

        <div ng-click="alert()" class="btn btn-primary">Generate Alert</div>

    </div>
</body>
</html>

app.js (the logged message is successfully shown)

var app = angular.module('batchSparta', []);

app.run([

    function() {
        console.log("Angular is running!");
    }
]);

invite.js

app.controller("InviteController", function($scope) {
    $scope.alert = function($scope) {
        alert("Alert triggered");
    }
})

Upvotes: 1

Views: 88

Answers (1)

Marc Kline
Marc Kline

Reputation: 9409

You have ng-app set on the head element, so when Angular bootstraps, it's initializing your app in an area where your controller isn't (and can't be) located.

This explains why you're seeing the run log; and yet, your controller doesn't work.

Unless your Angular app is meant to reside on only a portion of the page, you can safely set the attribute on the html tag to have it encompass the whole page:

<html lang="en" ng-app="batchSparta">

Demo

Upvotes: 4

Related Questions