Encountering an issue with Angular 1.6 and webpack: controller registration problem

Currently developing a small application with Angular for the frontend, and my frontend module is structured as follows:

https://i.stack.imgur.com/tjfPB.png

In the app.js file, the main Angular module 'weatherApp' is defined:

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

The controller (weather.js) registers WeatherCtrl:

angular.module('weatherApp')
.controller('WeatherCtrl', ['$scope', 'WeatherProvider', ($scope, WeatherProvider) => {
    $scope.location = {
        city: "",
        country: ""
    };

    $scope.options = [
        { label: "Weather", value: "weather" },
        { label: "Forecast", value: "forecast" }
    ];
    $scope.selected = $scope.options[0];

    $scope.result = "Empty";

    $scope.getWeather = function () {
        WeatherProvider.getWeatherFunc($scope.selected.value, $scope.location.city, $scope.location.country)
        .then((response) => {
            $scope.result = response.data;
        })
     }
}]);

Meanwhile, the service (provider.js) registers WeatherProvider:

angular.module('weatherApp')
.service('WeatherProvider', ['$http', function($http) {
    this.getWeatherFunc = (weatherMode, city, country) => {
        return $http({
            method: 'GET',
            url: "http://localhost:8080/" + weatherMode + "/" + city + "/" + country
        })
    }
}]);

Here's a glimpse of my webpack configuration:

var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
   devServer: {
       disableHostCheck: true
   },
   target: 'web',
   context: path.join(__dirname, "src"),
   devtool: 'source-map',
   entry: {
       app: "./app.js",
   },
   resolve: {
       modules: [
           path.resolve(__dirname),
           "node_modules"
       ],
       extensions: ['.js', '.html']
   },

   module: {
       loaders: [
           {
               test: /\.js$/,
               exclude: /node_modules/,
               loader: 'babel-loader',
           }
       ]
   },

   output: {
       path: path.join(__dirname, 'src'),
       filename: "bundle.js",
       publicPath: "/"
   },

   plugins: [
       new HtmlWebpackPlugin({
           template: __dirname + "/src/index.tmpl.html"
       }),
       new webpack.DefinePlugin({
           'process.env': {
               'NODE_ENV': JSON.stringify(process.env.NODE_ENV ||"dev"),
           }
       })
   ],};

Displayed below is the content of index.tmpl.html:

https://i.stack.imgur.com/WsGDm.png

Upon running npm run dev, accessing http://localhost:8081/ shows the following outcome:

https://i.stack.imgur.com/trUe6.png

An error message indicates: Error: $controller:ctrlreg - A controller with this name is not registered. However, visiting http://localhost:8081/index.tmpl.html displays the expected result:

https://i.stack.imgur.com/GfMH0.png

Could you suggest why my controller and service are missing from bundle.js? I suspect this is the primary cause of failure.

Answer №1

Experiment with rearranging the sequence:

<script src="app.js"></script>
<script src="service/provider.js"></script>
<script src="controller/weather.js"></script>

Answer №2

I had been mistakenly using a incorrect webpack configuration example, the particular line was not suitable for my specific case:

target: 'web'

Once I switched it to:

target: 'node'

everything fell into place and started functioning as intended.

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

How to retrieve a string from a regular expression in Javascript without [Object object] output

Within my code, there exists a parent form component and a child component used for auto-completing text input. The Parent component passes an array of objects named autoCompTxt, consisting of name and id fields, to the Child component. //Parent: const [ob ...

Converting a curl command to a $.ajax() call in JavaScript: A step-by-step guide

I'm attempting to retrieve data from the Zomato API by using jquery ajax, however, they have provided a curl command instead. curl -X GET --header "Accept: application/json" --header "user-key: key" "https://developers.zomato.com/api/v2.1/cities" Is ...

Refresh the context whenever the state object changes

Within my application, I am utilizing a PageContext to maintain the state of various User objects stored as an array. Each User object includes a ScheduledPost object that undergoes changes when a user adds a new post. My challenge lies in figuring out how ...

Exploring the integration of query parameters in Postman using mongoose

In my code, I have a driver.js file that holds a driver schema, and a driverController.js file with REST methods including GET, POST, DELETE, and PUT. What I want to achieve is to send a GET request to http://localhost:3000/drivers?available=true This re ...

What causes the discrepancy in smoothness between the JavaScript animation when offline versus its choppiness when online, particularly on AWS

Recently I delved into game development using HTML5/CSS/JS and embarked on a small project. Check out the game here at this AWS storage link: If you open the game and press SPACE, you'll notice that the ball starts moving with occasional brief pauses ...

Angular does not wait for the backend service call response in tap

Does anyone have a solution for subscribing to responses when the tap operator is used in a service? edit(status) { dataObj.val = status; // call post service with status.. this.service .update(dataObj) .pipe(takeUntil(this._n ...

What is the formula to determine if x is greater than y and also less than z?

I need help determining if a number falls within the range of greater than 0 but less than 8 using JavaScript. Can anyone assist me with this? Here is my attempt at it: if (score > 0 && score < 8) { alert(score); } ...

Using shortcode to enhance wordpress post content

I am trying to implement a feature similar to the one found at http://jsfiddle.net/theimaginative/gA63t/ within a wordpress post. I have attempted to create a shortcode for inserting this into a post, but I am encountering difficulties. While I have been s ...

Dynamic parameterization of Angular form controls

I'm facing an issue with adding validators to a form where some controls are required only if a specific condition is met by another control. I initially created a custom validator function that takes a parameter to determine the requirement, but the ...

Mean Stack involves the interaction between the client controller and the server controller using routes to communicate and call server methods

I am currently developing a mean stack application and encountering difficulties when attempting to send requests to the Express/Node server in order to delete an element from an array in Mongo. Below is my schema for reference: var DeckSchema = new Schem ...

Empty array returned when using fetch in a for loop

Currently, I am developing a server route to execute API calls. I have encountered the need to make two separate fetch requests as I require additional information that is not available in the first fetch. The issue lies in declaring a variable outside o ...

Decomposing a Vuex module into distinct files with Nuxt: A step-by-step guide

In the official Nuxt documentation (here), it is mentioned that 'You can choose to divide a module file into separate files: state.js, actions.js, mutations.js, and getters.js'. While there are examples of breaking down the Vuex store at the roo ...

Delay in Ionic list item navigation

As I continue to build my app using "$ ionic start myApp sidemenu" and deploy it directly to Android, I've noticed a significant delay when tapping on the playlist page, such as when selecting "Indie". It feels like there is a 300ms lag before the pag ...

Difficulty with Horizontal Mousewheel Scrolling

Struggling to implement a horizontal scrolling feature (via mousewheel) for both containers in the code below. I want this feature to be easily applied to any future container creations as well. <body> <style> #container { display: flex ...

Typescript controller inheritance leading to Error: $injector:unpr Unknown Provider due to minification

LATEST UPDATE: 2019/07/16 The issue I am facing is actually a result of misusing $inject. Instead of declaring it as private $inject in api-service.ts, it should have been public static $inject = [...]. During the minification process, explicit injection ...

What is the process for setting up extra routes in an Express server that is configured to work with React-Router

Currently, my server is set up to return index.html for every app.use(/* API call that is made. When I try to create a new route using app.get('/info', it still returns the index.html file. I am looking for a way to add new routes without having ...

Developing a Form Submission Feature Using JQuery Mobile

I'm having trouble submitting a form using JQuery Mobile. Currently, my code looks like this: <form action="#pagetwo" method="post" name="myform"> <input type="text" name="myname"> <input type="submit" value="submit" /> ... and th ...

Issue: TableHead inside an Expandable Row in MUI-Datatable is being duplicated for each row, causing the table to not be centered.Explanation: The

Can anyone help me with this issue? I'm having trouble with my table where the headings are repeating for every row and the table is stuck on the far right side. How can I center the table instead? Codesandbox: https://codesandbox.io/s/xenodochial-fo ...

Using node.js with express to send data stored in a variable to the browser instead of displaying it in the

I'm currently getting the hang of node.js. It's pretty straightforward to use res.send and output some basic "hello world" text, but how can I pass variables to the browser instead of just to the console? Here is a snippet of code: var Tester = ...

Achieving Horizontal Alignment of Tab Labels and Icons in Material-UI with Tabs API

I am currently attempting to customize the Material UI CSS in order to align both the phone icon and text on the same line and closer together. After doing some research, I stumbled upon the Tabs API which seemed promising. Upon further inspection, I disc ...