简体   繁体   中英

Having trouble setting up AngularJS

So I was trying to setup something really basic, but can't figure out for the hell of me why angularjs is not displaying the stuff inside the curly brackets. I'm utterly stumped

link to the plunker: http://plnkr.co/edit/GfCgemAxZPkhKNv7A0Av?p=preview

index.html:

<!DOCTYPE html>
<html ng-app>

  <head>
    <script data-require="angular.js@*" data-semver="2.0.0-alpha.27" src="https://code.angularjs.org/2.0.0-alpha.27/angular.js"></script>
    <link rel="stylesheet" href="mainstyle.css" />
    <script src="script.js"></script>
    <script src="maincontroller.js"></script>
  </head>

  <body>
    <div ng-controller="maincontroller">
      <p>{{introduction}}</p>
    </div>

  </body>

</html>

script.js:

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

maincontroller.js

app.controller('maincontroller', maincontroller);

var maincontroller = function($scope) {
  $scope.introduction = "Welcome to My Program";
}

There are 3 errors that you could see if you take a look at your js console of your browser. I updated your plunkr .

404 & angular undefined

The link to angular was simply wrong.

Cannot read property controller of undefined

In your maincontroller.js you tried to add a controller before you defined the function. A better approach taken from the angular docs :

app.controller('maincontroller', ['$scope', function($scope) {
  $scope.introduction = "Welcome to My Program";
}]);

Argument maincontroller is not a function

This time the console even gives you a link with a description of the problem. The cause is, that you forgot to set the ng-app attribute to your app:

ng-app="myProgram"

There are a couple of issues.

You forgot to reference your main module in the html:

<html ng-app="myProgram">

You have a broken link to angular.js. Use the CDN link as provided on the angular site .

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

You assign maincontroller before it is defined. One way to fix this is by simply not assigning it to a variable first:

app.controller('maincontroller', function($scope) {
  $scope.introduction = "Welcome to My Program";
});

A more general tip: check out this seed project for a best practice on how to organize angular apps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM