Exploring the features of AngularJS, one can delve into the ControllerAs syntax

Currently, I am in the process of developing a directive and following the guidelines outlined in the John Papa style guide. In line with this, I have adopted the ControllerAs syntax approach and implemented a small directive as shown below:

(function() {
    angular
        .module('htApp')
        .directive('newsletterSignup', newsletter_signup);

    function newsletter_signup($http) {
        var directive = {
            templateUrl: '../whatever.tpl.html',
            restrict: 'EA',
            controller : controller,
            controllerAs: 'vm',
            bindToController: true
        };

        return directive;

        controller.$inject = ['$http'];

        function controller($http) {
            var vm = this;
            
            function doSubmit(form) {
                debugger;
            };

            vm.doSubmit = doSubmit;
        }
    }
})();

This directive serves as a newsletter signup service. It requires an HTTP request, hence why it is injected into the controller. However, a complication arises when attempting to access the $http service within the doSubmit() function.

Hence, my inquiry: how can I make use of the injected $http within the doSubmit() function effectively?

UPDATE

The view code will be included for reference purposes, although it functions correctly:

<button class="btn btn-yellow" ng-click="vm.doSubmit(newsletterform)" translate>
    footer.ok_button_text
</button>

UPDATE 2

Upon further investigation, it appears that @Tek was correct – the code does indeed work. The reason for my initial confusion could possibly be due to Chrome's JS runtime optimizing the $http when it recognizes that it won't be called.

https://i.sstatic.net/GgDZJ.png

The current implementation functions properly because the runtime anticipates the usage of $http in the console.log() statement. However, upon removing that line, a new issue arises:

https://i.sstatic.net/oea5x.png

When the console.log line is commented out, resulting in no utilization of $http in the doSubmit() call, accessing $http from the console displays it as undefined.

Answer №1

The issue lies here:

return directive;

controller.$inject = ['$http'];

function controller($http) {
...

When the return statement is executed, the controller function is defined but controller.$inject will never be defined. Additionally, the newsletter_signup function does not have the corresponding $inject.

Click here for a demo that may not minify properly, and here for one that will.

Answer №2

It appears that your demonstration is functioning properly: example.

In my opinion, John Papa's approach to angular style seems unconventional; I personally prefer this style guide.

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

Verify the text file for any data, and if it contains any, display it on the web browser using JavaScript

I have a program in C that works with a temperature sensor. It creates a file to store the temperature and indicates whether it falls within specific values. I want to display this data on a web browser and update it every 5 minutes. I'm looking for ...

Creating Location-Specific Customer Data using AngularJS similar to Google Analytics

Looking to create a user registration map similar to Google Analytics without actually using Google Analytics. Can anyone provide assistance with this task? I am utilizing MVC, C#, Sql Server-2014, AngularJS, and jQuery for this project. Despite my efforts ...

Tips for refreshing the direction route in google-maps-react

I have an array of coordinates, and when I add a new coordinate to the array, I want the route direction on the map to update accordingly. This is the code snippet from my googlemap.js file: /* global google */ import React, { Component } from "react ...

Cypress: harnessing the power of regular expressions within jQuery selectors for the ":contains()" method

Trying to use Cypress along with a regular expression to target an element that includes specific text. The following get() function successfully works: cy.get('[data-cy=tile]').contains(new RegExp(myVar)) However, the following command does no ...

Searching for a specific match in JSON data using React streaming technology: encountering issues with the .find method as

Having experience with functional programming in Java, I recently ventured into JavaScript. My current task involves streaming through a JSON output structured like this: { "originatingRequest": { "clientId": 1, "simulationName": "Sea ...

The EJS templating system

I am currently working on a node.js project and I have an ejs template file that utilizes templates for the header and footer. The structure of template.ejs is as follows: <%- include(header) %> main content <%- include(footer) %> <script ...

The window fails to retain the scroll position when overflow is enabled

Whenever I click on a specific div, I use jQuery to dynamically apply overflow: hidden to the html and body. $(".mydiv").on("click", function() { $("html, body").css("overflow", "hidden"); }); However, this action causes the window to scroll to the to ...

Mastering the Art of Unit Testing JavaScript Asynchronous Code with Jasmine Mocking

Hello, I recently started learning JS and encountered a problem while testing asynchronous methods with jasmine mocking. Below is the code snippet I am trying to test: test.factory('service', ['$http', '$q', function($http, ...

What is the best way to create a new object in a Vue component with optimal efficiency?

Currently, I am working on initializing a map that would be utilized in my calculatePrice function. calculatePrice(key) { let prices = new Map({ 0: 17, 1: 19, 2: 24, 3: 27, 4: 30, 5: 46, 6: 50 ...

Having trouble running Javascript with jQuery's ajax load()?

I have encountered this problem and despite reading multiple posts, I am unable to find a solution. My challenge lies in loading an HTML file into a div that contains an unordered list. The list is supposed to function as an expanded menu with sub-items, ...

having trouble compiling a react js file with webpack

One of my files, app.js, contains the following code snippet: handlePageClick = (data) => { let selected = data.selected; let offset = Math.ceil(selected * this.props.perPage); this.setState({offset: offset}, () => { this.setStat ...

AngularJs tip: Harness the power of parallel and sequential function calls that have interdependencies

service (function () { 'use strict'; angular .module('app.user') .factory('myService', Service); Service.$inject = ['$http', 'API_ENDPOINT', '$q']; /* @ngInject ...

Sending both an array and an image via Ajax in a single request

I need to send both JSON and file data to my PHP backend using an ajax call. Here is my current ajax call: $.ajax({ type: 'POST', dataType: 'json', data: jsonData, url: 'xxx.php', cache: false, suc ...

Saving the initial and final days of each month in a year using javascript

I am trying to create an array of objects that contain the first and last day of each month in the year. I have attempted a solution but have hit a roadblock and cannot achieve the desired results. module.exports = function () { let months_names = ["j ...

Convert an AJAX JSON object into values for multiple text boxes

When making an ajax call, I receive the following JSON input: var json = { "id_u":"1", "nombre_usuario":"JESUS", "apellido_paterno_usuario":"DIAZ", } I have text inputs that correspond to each key in the JSON object: <input type="text" name="id ...

Receiving partial data through the API

My PHP API seems to be experiencing issues when I send data to it using either a post or get request. The strange thing is that the API receives only half of the data. This API functions perfectly fine on localhost, but encounters errors when used on the p ...

Iterate through each entry in the database and identify and fix any duplicate records

In my form, I have a JSON array that includes the name and value of each input. I am attempting to add an "optionprix" attribute for each input with the "optionname" class based on the corresponding value of the input with the "optionprix" class. Here is ...

In Angular's production build on Webkit/Safari, the left-hand side of the operator '=' must be a reference

Recently, I completed a project using Angular. After successfully building it for production without any errors, everything seemed to work perfectly on Chrome. However, when attempting to run the app on Webkit/Safari, an error was displayed in the cons ...

Are the shadows in the scene being affected by a problem between DirectionalLightHelper and CameraHelper?

Currently, I am working on a complex static render in the browser using three.js and I have encountered an issue while trying to produce accurate shadows with a single THREE.DirectionalLight that represents the sun in my scene. All the geometry in another ...

The PHP Ajax code runs a for loop twice, but the data is only stored once during its execution

<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> <body onload="searchVideo();"> <script> var data_length = 2; for(var i=0; i<data_length; i+ ...