What could be improved in this AngularJS code snippet?

Currently, I am immersed in an AngularJS book and have extracted the following code snippet directly from its pages:

<!DOCTYPE html>
<html ng-app='myApp'>
<head>
    <title>Your Shopping Cart</title>
</head>
<body ng-controller='CartController'>
<h1>Your Order</h1>
<div ng-repeat='item in items'>
    <span>{{item.title}}</span>
    <input ng-model='item.quantity'>
    <span>{{item.price | currency}}</span>
    <span>{{item.price * item.quantity | currency}}</span>
    <button ng-click="remove($index)">Remove</button>
</div>
<script src="js/lib/angular.min.js"></script>
<script>
    function CartController($scope) {
        $scope.items = [
            {title: 'Paint pots', quantity: 8, price: 3.95},
            {title: 'Polka dots', quantity: 17, price: 12.95},
            {title: 'Pebbles', quantity: 5, price: 6.95}
        ];
        $scope.remove = function(index) {
            $scope.items.splice(index, 1);
        }
    }
</script>
</body>
</html>

Although I've ensured that angular.min.js is correctly included, Chrome presented me with the following output:

Evidently, there seems to be an issue within the code. However, being a novice, I'm unable to pinpoint the exact problem. Any assistance or guidance on this matter would be greatly appreciated. Thank you.

update

The error output provided by Chrome is as follows:

Failed to instantiate module myApp due to:
Error: [$injector:nomod] http://errors.angularjs.org/1.2.10/$injector/nomod?p0=myApp
    at Error (native)
    at http://localhost:63342/angular-book/js/lib/angular.min.js:6:450
    at http://localhost:63342/angular-book/js/lib/angular.min.js:20:260
    at http://localhost:63342/angular-book/js/lib/angular.min.js:21:262
    at http://localhost:63342/angular-book/js/lib/angular.min.js:29:175
    at Array.forEach (native)
    at q (http://localhost:63342/angular-book/js/lib/angular.min.js:7:280)
    at e (http://localhost:63342/angular-book/js/lib/angular.min.js:29:115)
    at $b (http://localhost:63342/angular-book/js/lib/angular.min.js:32:232)
    at Zb.c (http://localhost:63342/angular-book/js/lib/angular.min.js:17:431

Answer №1

In order to integrate the CartController into your application "myApp," it is necessary for you to register it.

One method to achieve this is as follows:

angular.module('myApp').controller('CartController', ['$scope', function ($scope) {
        $scope.items = [
            {name: 'Tennis shoes', quantity: 6, price: 59.99},
            {name: 'Baseball cap', quantity: 3, price: 19.99},
            {name: 'Water bottle', quantity: 2, price: 9.99}
        ];
        $scope.remove = function(index) {
            $scope.items.splice(index, 1);
        }
    }]);

Answer №2

The book on AngularJS from O'Reilly is riddled with errors that require extensive code sample corrections.

In your app, make sure to reference the name of the app at the top but also register it properly:

<html ng-app='myApp'>

If you assign a value here, don't forget to define the module as well:

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

You can even assign the module to a variable for easy access when creating controllers, etc:

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

myApp.controller('myController',
  function myController($scope){
};

For a simple Angular app using only one page of code, you can skip assigning a value to the ng-app attribute:

<html ng-app>

Here's the complete working code example I used:

<!doctype html>
<html ng-app>
<head>
    <meta charset="utf-8">
    <title>Your Shopping Cart</title>
</head>

<body ng-controller='CartController'>
    <h1>Your Order</h1>
    <div ng-repeat='item in items'>
        <span>{{item.title}}</span>
        <input ng-model='item.quantity'>
        <span>{{item.price | currency}}</span>
        <span>{{item.price * item.quantity | currency}}</span>
        <button ng-click="remove($index)">Remove</button>
    </div>

    <script src="js/angular.min.js"></script>
<script>
function CartController($scope) {
    $scope.items = [
        {title: 'Paint pots', quantity: 8, price: 3.95},
        {title: 'Polka dots', quantity: 17, price: 12.95},
        {title: 'Pebbles', quantity: 5, price: 6.95}
    ];
    $scope.remove = function(index) {
        $scope.items.splice(index, 1);
    }
}
</script>
</body>
</html>

Answer №3

Like Luke previously mentioned, it is essential to establish the myApp framework. Make sure to properly inject dependencies such as controllers and directives into myApp:

angular.module('myApp', [
  // Inject myApp dependencies (controllers, etc.) here...
    'myApp.controllers'
]).
config(['$routeProvider', function($routeProvider) {
  // Define your routes here...
}]);

Next, create your controller, which will be injected...

angular.module('myApp.controllers', []).
  controller('MyCtrl', [function() {

  }]);

If you haven't already, check out the Angular seed project. It serves as a valuable resource for those getting started with Angular.

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

Navigating with Reach Router only updates the URL, not the component being rendered

Is there a way to programmatically navigate using Reach Router in React? I have noticed that when updating the URL, the route does not render. Even though the URL changes, the original component remains displayed according to the React developer tools. Ho ...

JavaScript checking the current page's URL is crucial for maintaining accurate and dynamic

I've attempted to verify the URL using this specific function. It functions properly with single text, but fails when a URL is inputted. jQuery(document).ready ( function () { //var regExp = /franky/g; //It works fine ...

Express and Angular2 Webpack integration

Recently, I set up Angular 2 with Webpack and explored its routing capabilities through a sample app. I am now interested in integrating Angular2 for front end routing while utilizing ExpressJS for a RESTful API backend on the same server. For example, ht ...

Causing a click event to occur results in crashing the browser

Take a look at this link: example on jsfiddle Why does the click event keep triggering multiple times when a div is clicked, eventually causing the browser to crash? What could be causing this issue and how can it be resolved? The actual div contains a l ...

When attempting to download a PDF file from Flask to the client, the file appears to be

I am encountering an issue with my Flask server that sends a PDF file using the send_file function. When testing this route on Postman, I am able to view and download the PDF successfully. However, when attempting to download it through my React frontend, ...

Can JavaScript be used to modify the headers of an HTTP request?

Can JavaScript be used to modify or establish HTTP request headers? ...

What is the best way to extract URLs with varying numbers of slashes in angular.js?

My goal is to create an Angular website focused on managing files, allowing users to navigate through a file system tree similar to how it's done on Github (example: github.com/angular/angular.js/tree/master/path/to/my/file.js. I want to extract the ...

Restrict the duration of time a user can spend in the v-calendar

I'm currently developing a project where users can request appointments. I'm utilizing the v-calendar library, which incorporates a datepicker. The challenge I'm facing is that users are able to request appointments at any time of day, 24/7 ...

Delay Export of React Component Until After Request in Shopify App Development

Being a newbie in Shopify App Development, React, and Next.js, I may have a silly question. Currently, I am making a request to a website and using the response in the React component that I want to export/render. To avoid it being undefined, I need to wai ...

Waiting in Python using Selenium until a class becomes visible

Currently, I am trying to extract information from a website that has multiple web pages. This is how my code appears: item_List = [] def scrape(pageNumber): driver.get(url + pageExtension + str(pageNumber)) items = driver.find_elements_by_class_ ...

Deleting tasks from the to-do list using Node.js and Express with EJS

Looking to implement functionality where each list item can be removed from a Node.js array by clicking on an HTML button using EJS and Express: I am considering placing an HTML button next to each list element so that the selected element can be removed ...

What is the best way to group/merge multiple objects that have the same name into a single object (Nesting)?

I have a dataset containing students' names and their marks in different subjects stored as an array of objects. My goal is to merge the data into a single object for each student with matching names, resulting in one record per student. Here is an ex ...

Tips on Guaranteeing AJAX Requests are Successfully Called in Sequential Order and Receive Responses in the Same Sequence

What is the best way to guarantee that AJAX requests are executed in a specific order and receive responses in the same order? ...

Utilizing AngularJS "controller as" syntax within templates

Recently diving into the AngularJS world, I embarked on setting up a simple laravel/angular JWT authentication by following this specific tutorial. My goal is to utilize the "Controller As" syntax instead of relying on $scope as instructed in the tutorial ...

Unveiling the mystery: Locating the position of an element within a multidimensional array using JavaScript or JQuery

How can I retrieve the index of a specific element in a JSON array converted from a PHP array using json_encode, using JavaScript or JQuery? Initially, the user will choose an option where the values correspond to people's IDs. <select class="for ...

Significant issue identified with ajax functionality, requiring immediate attention

After executing the code in the console, I expected to see the ajax object with a readyState of 0 (as I aborted the ajax call). However, Chrome is displaying the number 4 in the console instead of 0. This discrepancy is surprising. http://jsfiddle.net/8yC ...

Complete and send HTML forms with changing IDs

I am facing an issue with storing data from two HTML forms with dynamic ID attributes using AJAX calls. Currently, the AJAX call only works for one HTML form with a static ID name "surveyImage". I am unsure how to individually call the submit() method for ...

Angular Inner Class

As a newcomer to Angular, I have a question about creating nested classes in Angular similar to the .NET class structure. public class BaseResponse<T> { public T Data { get; set; } public int StatusCo ...

Can we import a CSS file selectively in Vue.js?

Can specific css-files be applied only when the current route has a "forAdmin" meta in my Vue.js project that includes both an admin-panel and client pages? ...

What is the method for bringing in Mongoose to utilize json.parse()?

I'm really eager to utilize this code for importing a JSON file into JavaScript var treeData; var oReq = new XMLHttpRequest(); oReq.onload = reqListener; oReq.open("get", "test.json", true); oReq.send(); function reqListener(e) { treeData = JSON. ...