tri___ton tri___ton - 16 days ago 7
Javascript Question

Angular controller directly in index.html

I need to make a one page app without any additional files like app.js or controller.js

I created the example below, but I get the error:

Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.




<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> JavaScript Angular</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js">

var myАpp = angular.module("myАpp", []);

myАpp.controller("firstController", function($scope){
$scope.test = "test-to-test";

});

</script>
</head>
<body ng-app = "myApp">
<div ng-controller = "firstController">
{{test}}
</div>

</body>
</html>





So, is it possible to have only one file index.html with Angular and still have a controller inside?

Answer

You need to have the controller and module inside the <script> tag

<div ng-app="myАpp">
  <div ng-controller="firstController">
    <h1>{{test}}</h1>
  </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<script>
var app = 
    angular.module('myАpp', []).controller('firstController', function($scope){
  $scope.test  =  "test-to-test";
});
</script>

Comments