Problem with Angular controller

Recently delving into the world of angular.js, I encountered an issue while trying to run a basic controller example.

The error message reads: [ng:areq] http://errors.angularjs.org/1.4.7/ng/areq?p0=Mycontroller&p1=not%20a%20function%2C%20got%20undefined at Error (native)

Here is the code snippet from index.html:

<!DOCTYPE html>
<html ng-app>

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

  <script src="script.js"></script>
</head>

<body ng-controller="Mycontroller">
 <h1>{{message}}</h1>
</body>

</html>

And here's what is in script.js file:

var Mycontroller = function($scope){
  $scope.message = "Hello Angular";
};

The output displays as follows:

{{message}}

Could someone help me identify where I have gone wrong?

Answer №1

To follow the Angular way, it is recommended to create a module and then attach a controller to it. Your code structure should resemble the following:

<html ng-app="my-app">

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

  <script src="script.js"></script>
</head>

<body ng-controller="Mycontroller">
 <h1>{{message}}</h1>
</body>

</html>

Make sure your JavaScript file contains the following:

angular.module('my-app', [])
    .controller('Mycontroller', function($scope) {
         $scope.message = "Hello Angular";
    });

You can also check out the Plunker example here: http://plnkr.co/edit/tYIQOlNALzco9zobAIO0?p=preview

Answer №2

give this a try, it's effective

Web Design Code Example

 <!doctype html>
 <html ng-app="MyApp">
    <head>
    <title>Sample HTML Page</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
    <script src="hello.js"></script>
  </head>

<body>
    <div ng-controller="Hello">

        <p>The ID is {{greeting.id}}</p>
        <p>The content is {{greeting.content}}</p>
        <p>{{message}}</p>
    </div>
</body>

hello.js

      var app = angular.module("MyApp", []);
     app.controller("Hello", function($scope, $http){Helloz($scope, $http);});
     function Helloz($scope, $http) {
     //$http.get('http://rest-service.guides.spring.io/greeting').
     $http.get('/person').
       then(function(data) {
         $scope.greeting =angular.fromJson(data).data;
         $scope.message=angular.fromJson(data).data;
     },null);
 }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Simulated 'paths' configuration in non-TypeScript Node.js environment

In my TypeScript project, I've utilized a helpful configuration option in tsconfig.json that enables me to set up aliases for folders. { "compilerOptions": { "paths": { "@src/*": ["src/*"], "@imag ...

Highlight a pair of words in a phrase using jquery technology

Only one word in my code is highlighted $(document).ready(function() { let firstword = 'web'; let secondword = 'js'; $(".field.ConditionsAccept>.caption:contains('" + secondword + "'):contains('" + firstword ...

Utilize Javascript to generate intricate table headers based on JSON data

I am currently facing a challenge in creating an HTML table header with colspan. I have a JSON object as follows: var metadata = [{ "colIndex": 0, "colType": "String", "colName": "PM" }, { "colIndex": 1, "colType": "String", "colName": "PR ...

Error: The module cannot be located due to a recursion issue in resolving within the Angular application

Trying to import my module import { waitProp } from 'wait-prop'; Encountering the following error: ERROR in ./src/app/qr-scanner/qr-scanner.component.ts Module not found: Error: Recursion in resolving Stack: resolve: (/Users/gkucmierz/workspac ...

Is it possible to manipulate a parent component's state with a child component?

I have been experimenting with Material UI's react modal to create a modal as my child component. In the parent component, I have set up a state that controls the visibility of the modal and added a button inside the modal to close it. However, this s ...

What could be the reason for the 'tsc' command not functioning in the Git Bash terminal but working perfectly in the command prompt?

I recently installed TypeScript globally on my machine, but I am facing an issue while trying to use it in the git bash terminal. Whenever I run tsc -v, I encounter the following error: C:\Users\itupe\AppData\Roaming\npm/node: l ...

``There seems to be an issue with implementing the SlideDown feature in JavaScript

I am having an issue with a code where the expected behavior is to slide down a div when a person hovers over text, but it's not working. Can someone please review and identify the cause of this problem? <script type="text/javascript" src="/js/jqu ...

Angular Translate - Utilizing translate-values attribute for translation

Having trouble using angular translate with dynamic translation values that need to be translated first. If you want a better explanation of the issue, check out this plunker: PLUNKER <p translate="PARAGRAPH" translate-values="{username: ('us ...

Guide on exporting type definitions and utilizing them with npm link for a local package

I am in the process of developing a new testing tool called tepper as an alternative to supertest. My goal is to make this package available in both ESM and CJS formats. However, I'm encountering an issue where users of the library are unable to locat ...

Ways to combine two arrays using dual requests in JavaScript with Mailchimp

The issue with the title not being very clear has been noted. Allow me to elaborate on my problem. Below is the code snippet: mailchimpMarketing = require("@mailchimp/mailchimp_marketing"); mailchimpMarketing.setConfig({ apiKey: "MY API KEY", server: "MY ...

Certain public files in Express cannot be accessed locally

While running my Node.js application on localhost, I am able to access http://localhost:3000/css/dashboard.css without any issues. However, when attempting to access http://localhost:3000/css/logo.png for a logo image in the same directory, all I receive i ...

What is causing the extra space on the right side of the box?

I've been struggling to align text next to an image inside a box. Desired outcome CSS: #roundedBox { border-radius: 25px; background: #363636; width: auto; height: auto; margin: 10%; display: flex; position: relative; ...

Steer clear of utilizing Number() when working with scientific notation

I am attempting to perform the following task Number("0.00000000000122") yields 1.22e-12 However, my goal is to convert that number from a String to a Number. console.log(Number("0.00000000000122")) ...

Tips for eliminating all line breaks in a Node JS application's console log statement

I am currently working on a NodeJS application using Express. While logging is functioning correctly for most files and libraries, I have noticed that many of them, even those beyond my control, contain line breaks in the logs. My objective is to ensure ...

Accessing html form elements using jQuery

I'm having trouble extracting a form using jQuery and haven't been able to find a solution. I've tried several examples, but none of them display the form tags along with their attributes. Here is a sample fiddle that I've created: Sam ...

Tips for finding the *index* of distinct values in an array

My goal is to identify the indexes of unique values in an array. While I've come across various methods for removing duplicate values from an array, such as those found here: How to get unique values in an array I'm currently struggling to find ...

When utilizing JSON data in node.js, the .find() method may return undefined

I am currently working on a node server and my goal is to display JSON data when a specific ID is clicked. I have configured a dynamic URL that will retrieve the data of the clicked video using parameters and then compare it with the data in the JSON file ...

Changing the value of a form input name after a $scope.$watch event is activated

In my AngularJS 1.4 project, I have a form input element where I am attempting to dynamically set the name attribute. <input type="email" name="{{ctrl.name}}" class="form-control" id="email" ng-minlength="5" required> The assignment of the name att ...

React is indicating that returning functions is not appropriate as a React child. This issue may arise if you accidentally return a component instead of <Component /> within the render method

Check out the main game.js and app.js files: //Here is the code in game.js// import React, { Component } from "react"; class Game extends Component { constructor(props) { super(props); this.state = { num: 0 }; this.numPicker = this.numPi ...

Using PHP in combination with Ajax for automatically performing an action when there is an update

My goal is to have the latest value entered in the database trigger the playing of a specific song. For instance, if someone on the other side of the world selects a song on their phone, that same song should automatically start playing on all devices with ...