javascriptangularjsangularjs-1.5

angular js1 basic application using http-server doesn't enter the controller


Below is the index.html file:

<html ng-app="myApp">
<head>
  <title> My Contacts App </title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
  <script src="app.js"></script>
  <link rel="shortcut icon" href="favicon.ico"></link>
</head>
<body>
  <h1>My contact App </h1>
  <div controller="contactCtrl as ctrl">
    {{ ctrl.nm }}

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

app.js is as shown below:

var app = angular.module("myApp",[]);
app.controller("contactCtrl",createContacts);

function createContacts()
{
  this.nm = "Hey";

console.log("INside controller");
}

Problem: When I start http-server from the same directory where the source files are and type http://127.0.0.1:8080 the browser just displays static html content. It neighter displays the value of the variable "nm" nor shows anything from console.log I am at a beginner level. TIA.


Solution

  • This should be ng-controller:

     <div ng-controller="contactCtrl as ctrl">
       {{ ctrl.nm }}
     </div>
    

    Here is an example on how to use the ng-controller directive in the html:

    var app = angular.module("myApp",[]);
    app.controller("contactCtrl",createContacts);
    
    function createContacts()
    {
      this.nm = "Hey";
    
    console.log("INside controller");
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <html ng-app="myApp">
    <head>
      <title> My Contacts App </title>
      <script src="app.js"></script>
      <link rel="shortcut icon" href="favicon.ico"></link>
    </head>
    <body>
      <h1>My contact App </h1>
      <div ng-controller="contactCtrl as ctrl">
        {{ ctrl.nm }}
      </div>
    </body>
    </html>