Search code examples
javascriptangularjsplunker

Simple Angular js Not Working on Plunker


Can you please take a look at This Plunker Demo and let me know why it is not working?

here is the code I have

<!DOCTYPE html>
<html ng-app>

  <head>
    <script data-require="[email protected]" data-semver="2.0.0-alpha.31" src="https://code.angularjs.org/2.0.0-alpha.31/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-controller="FirstController">
      <h1>{{msg}}</h1>
    </div>
  </body>

</html>

and in script.js:

var FirstController = function($scope){
    $scope.msg = "This Must Work!";
};

Solution

  • Do you want to use angular or angular 2? Angular 2 is in beta right now and not the commonly used version.

    In case of angular 1, there are some small mistakes.

    First of all, you didn't declare the app in your javascript. To do this you should write something like this:

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

    Then, you used the ng-app directive, but didn't provide a value for it. It should be the same value as the 'module' you made previously (myApp in this case).

    <html ng-app="myApp">
    

    Next, to be able to use a controller in your app, you have to 'attach' it to your app. Otherwise, angular doesn't know it's existence. We do this like so:

    myApp.controller('FirstController', ['$scope', function($scope) {
      $scope.msg = 'This Must Work!';
    }]);
    

    I also used the angular CDN for this example.

    And a working Plunkr demo