Encountered an error with an unregistered controller in the same application while using two

Let me set the scene:

Here are snippets from both the JS file main.js and the HTML file index.html:

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

angular.module("myApp", []).controller("postController", function($scope) {
    $scope.buttonName = "Post";
})

angular.module("myApp", []).controller("myController", function($scope) {
    $scope.ButtonStatus  = "OFF";
    $scope.myStyle = buttonGreen; //{'background-color':'#00FF00', 'font-size': '24px', 'width': '80px'}
    $scope.toggleRelay = function(){
        if($scope.ButtonStatus == "OFF")
        {
            $scope.ButtonStatus = "ON";
            $scope.myStyle = buttonRed;
        }
        else
        {
            $scope.ButtonStatus = "OFF";
            $scope.myStyle = buttonGreen;   
        }
    }
})
<body ng-app="myApp">
    <h1 id="the-header">Welcome to home electricity manager!</h1>
    <div add-row ng-controller="myController" style="text-align: center; display: inline-block;">
        <span style="white-space:pre;">Button text</span><br/>
        <button id="first-button" ng-style="myStyle" ng-click="toggleRelay()" id="switch-circuit-1">{{ButtonStatus}}</button>
    </div>
    <div add-row ng-controller="myController" style="text-align: center; display: inline-block;">   
        <span id="second-button" style="white-space:pre;">{{buttonOneText}}</span><br/>
        <button ng-style="myStyle" ng-click="toggleRelay()" id="switch-circuit-1">{{ButtonStatus}}</button>
    </div>
    <div ng-controller="postController" style="text-align: center; display: inline-block;">
        <button>ASSS</button>
    </div>
</body>

Upon running this code, I encountered this error. The objective was to use two controllers within the same app, but it appears to be causing issues. Removing the postController resolves the problem. I've explored various resources on incorporating multiple controllers in a single app, but none seem to work for my particular setup.

Answer №1

There is no requirement to redeclare a module with empty dependencies, consider the following approach:

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

angular.module("myApp").controller("postController", function($scope) {
    $scope.buttonLabel = "Post";
})

angular.module("myApp").controller("customController", function($scope) {
}

Answer №2

Avoid duplication with this script angular.module("myApp", []); Give this a shot

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

    myApp.controller('GreetingController', ['$scope', function($scope) {
      $scope.greeting = 'Bonjour!';
    }]);

Answer №3

// Here is a helpful code snippet for AngularJS development
// Make sure to include the array ['$scope', function($scope) {}] in your controller functions

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

app.controller("postController",['$scope', function($scope) {
    $scope.buttonName = "Post";
}]);

app.controller("myController", ['$scope',function($scope) {
    $scope.ButtonStatus  = "OFF";
    $scope.myStyle = buttonGreen; //{'background-color':'#00FF00', 'font-size': '24px', 'width': '80px'}
    
    $scope.toggleRelay = function(){
        if($scope.ButtonStatus == "OFF") {
            $scope.ButtonStatus = "ON";
            $scope.myStyle = buttonRed;
        } else {
            $scope.ButtonStatus = "OFF";
            $scope.myStyle = buttonGreen;   
        }
    }
}]);

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

The event calendar feature in Codeigniter seems to only display one item of content at a time

I am encountering an issue with the event calendar where only 1 result is being displayed even though I have multiple exams scheduled on the same day that need to be shown. My query is fetching all the exams scheduled for the same day, however, it is not ...

What is the best way to verify a v-if condition with an array in Vue.js HTML?

I am looking to dynamically add rows based on multiple options selected from a dropdown menu. When I select one option at a time, I am able to get the desired result. However, when I select multiple options, no rows are added. For example, if I select opt ...

Issue with collapse functionality in Bootstrap not activating after using append()

Whenever the ajax call is successful, I am appending the content to the element with the id #special-contents. However, upon page load, the collapse button does not expand the panel. Below is my JavaScript code: $.ajax({ url: `${URL}/promotions/`, ...

Resetting text in an input field using CSS

Here is the fiddle link for reference: http://jsfiddle.net/a765q/1/. I noticed that when I click the reset button, the text color changes to grey. Any ideas on how to fix this? ...

Unable to download spreadsheet generated on the server side with Angular framework

I am currently attempting to download a spreadsheet generated by the server. The front-end of my application is built with Angular, while the back-end is powered by Java. Below is the method on the back-end that handles the request to generate and return ...

Tips for capturing the Three.js model file content and assigning it to a variable

After exporting a model from Blender to Three.js, the resulting file contains JSON data. There are two methods I know of for loading this model: var loader = new THREE.JSONLoader() var material = new THREE.MeshPhongMaterial({color: '#8080a0'}) ...

The function cannot be invoked. The 'Boolean' type does not have any call signatures. An error has occurred in the computed property of Vue3

Currently, I am working on creating a computed property that checks if an item is in the array. The function I have created returns a boolean value and takes one parameter, which is the item to be checked. isSelected: function (item: MediaGalleryItemTypes) ...

Check the JSON for verification, if not valid then throw an error during the fetch

ExampleObject serves as a representation of the expected output from the API endpoint. let ExampleObject={ "id":"", "name":"", "Body":"" } Is there a way to confirm that the response contai ...

Handle clicking on a mesh

I'm currently working on implementing a click event for a mesh (cube) in order to perform some processing tasks. var cubeFor3D = new THREE.Mesh(new THREE.CubeGeometry(40,80,40),img3D); scene.add(cubeFor3D); // renderer.render(scene,c ...

Deactivate the second subradio button when the first option is selected and vice versa

Need some assistance, hoping for your help. I have 2 choices with subcategories. 1 - Option A ---- variant 1 ---- variant 2 ---- variant 3 2 - Option B ---- variant 4 ---- variant 5 ---- variant 6 Check out my code here Users must choose betwe ...

Incorporating a self-invoking anonymous function to enhance Sir Trevor within an AngularJS framework while also making use of

I recently started working with AngularJS and I have an App where I am using the Sir Trevor content editor. I want to add some custom blocks to the editor by extending it, but I am having trouble accessing angular services within my extension code. The ext ...

Out of the total 1341 test cases, Yarn is currently only running 361

Currently, I am immersed in a project containing over 1300 test cases. Despite my efforts to clone the entire project again, it appears there is an issue with my npm. Upon executing yarn test, only 361 out of 1341 tests are running. I am puzzled as to how ...

Designing a versatile pop-up window with jQuery or JavaScript that functions seamlessly across all web browsers

I've encountered an issue with my code where it displays a popup message correctly in Chrome, but when testing it on Firefox and Edge, it creates a strange box at the end of the page instead. Here is the code snippet I'm referring to: var iframe ...

Exploring the comparison of information across two sets of databases using Node.js and MongoDB

In the realm of Node.js and MongoDB, I have set up two databases (1-btech2014 & 2-btechre2014) on a single server. My objective is to compare the data in btech2014 with that in btechre2014. If they match, I should retrieve the data from btech2014 as outpu ...

How can you nest a map within a map in JavaScript?

Here is the code snippet I am working with: _renderChannels() { return this.state.channelsData.map(channelData => { return this.state.channelsStreamData.map(channelStreamData => { return <Channel channelData={channelData} ch ...

Utilize directives or ng-click to dynamically update the preview within an AngularJS application

I am completely new to angularjs and have written a JavaScript function that I want to convert into a directive. My image library uses ng-repeat to display a set of images. Next to the images, there is a preview block that displays a larger version of the ...

Firestore behaving inconsistently by returning an empty promise even when data is available

I am working on an asynchronous function that retrieves tokens for a list of user ids. This function queries firestore to get the token associated with each user id within the list. async function fetchUserTokens(ids) { const promises = ids.map(async (id ...

Determining if a number exceeds 3 decimal points using AngularJS

I have encountered a problem where I need to determine if a value has more than three decimal places in AngularJS. Although I am familiar with checking if a value is a whole number or greater than zero, I am unsure how to perform this specific task. Below ...

Unexpected behavior with MongoDB update function

If I have a model like this: var stuffSchema = new mongoose.Schema({ "id": 1, "cars": { "suv": [], "sports": [], "supercar": [{ "owner": "nick", "previousOwners": [ ObjectId("574e1bc0abfb4a180404b17f"), ObjectId ...

Error: Unable to set 'type' property on a string - issue with radio button filters

When setting up radio button filters in Angular like this: <input type="radio" ng-model="filter.type" value="rose" class="type-filter"> Rose<br> <input type="radio" ng-model="filter.type" value="tomato" class="type-filter"> Tomato<b ...