Prateek Singla
Prateek Singla

Reputation: 709

How to work on MVC in AngularJS

I am getting this error Argument 'MyController' is not a function, got undefined when I am trying to run code below.

<!DOCTYPE html>
<html lang="en" ng-app>

<head>
  <meta charset="utf-8" />
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <title>Hello world from Prateek</title>
</head>

<body>
  <div ng-controller="MyController">
    <h1>{{author.name}}</h1>
    <p>{{author.title + ', ' + author.company}}</p>
  </div>
  <script>
    function MyController($scope) {
      $scope.author = {
        'name': 'J Doe',
        'title': 'Designer',
        'company': 'ABC XYZ'
      }
    }
  </script>
</body>

</html>

I want to get the name, title and company to be displayed, instead I am getting output as below

{{author.name}} {{author.title + ', ' + author.company}}

Upvotes: 0

Views: 38

Answers (2)

Shaishab Roy
Shaishab Roy

Reputation: 16805

you should create module first then create controller like:

var app = angular.module('myApp', []);
app.controller('MyController', function($scope) {
    $scope.author = {
        'name': 'J Doe',
        'title': 'Designer',
        'company': 'ABC XYZ'
      }
});

and in your html you should use ng-app="module-name" like:

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

Upvotes: 2

cubbuk
cubbuk

Reputation: 7920

You haven't defined any angular application in your javascript. You can define your controller using created module. Then you can access your controller from your views. Here is an example:

<!DOCTYPE html>
<html lang="en" ng-app ="myApp">

<head>
  <meta charset="utf-8" />
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <title>Hello world from Prateek</title>
</head>

<body>
  <div ng-controller="MyController">
    <h1>{{author.name}}</h1>
    <p>{{author.title + ', ' + author.company}}</p>
  </div>
  <script>
    var myApp = angular.module("myApp", []); // definition of a module, you use myApp in ng-app directive in the html part so that angularJS initialize itself.
    myApp.controller("MyController", function ($scope) {
      $scope.author = {
        'name': 'J Doe',
        'title': 'Designer',
        'company': 'ABC XYZ'
      }
    });
  </script>
</body>

</html>

Upvotes: 2

Related Questions