What is the best way to separate controller configuration into a dedicated file?

The angular configuration in the index.js file is as follows:

angular.module('ionicApp', ['ionic'])

    .config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {

        $stateProvider
            .state('entry', {
                url: '/entry',
                templateUrl: 'app/views/entry/entry.html',
                controller: 'EntryPageController'
            })


        $urlRouterProvider.otherwise('/entry');
    }])

    .controller('EntryPageController', ['$scope', '$state', function ($scope, $state) {
        $scope.navTitle = 'Entry Page';

        $scope.signIn = function () {
            $state.go('main.home');
        }
    }])

I am attempting to move the controller definition into its own file named entry-ctrl.js. Here is how I have set it up:

// file name entry-ctrl.js
(function () {
    'use strict';

    angular.module('ionicApp', ['ionic'])
        .controller('EntryPageController', ['$scope', '$state', EntryPageController]);

    function EntryPageController($scope, $state) {
        $scope.navTitle = 'Entry Page';

        $scope.signIn = function () {
            $state.go('main.home');
        }
    }
})
();

In index.html, I reference the file as:

<script src="app/views/entry/entry-ctrl.js"></script>

However, after making this change, the application does not behave correctly. The page does not appear as expected. Is there something else that needs to be done to use the code in the entry-ctrl.js file?

For reference, this is my entry.html content:

<ion-view title="{{navTitle}}" class="bubble-background">
    <ion-content has-header="true" padding="true">
        <h1>I'm working!</h1>
        <a class="button button-positive" ng-click="signIn()" ui-sref="main.home">Sign In</a>
    </ion-content>

</ion-view>

Answer №1

It appears that you have declared your angular app twice, once in index.js and again in entry-ctrl.js.

I recommend consolidating it as follows:

index.js

angular.module('ionicApp', ['ionic'])

    .config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {

        $stateProvider
            .state('entry', {
                url: '/entry',
                templateUrl: 'app/views/entry/entry.html',
                controller: 'EntryPageController'
            })


        $urlRouterProvider.otherwise('/entry');
    }])

entry-ctrl.js

(function () {
    'use strict';

    angular.module('ionicApp')
        .controller('EntryPageController', ['$scope', '$state', EntryPageController]);

    function EntryPageController($scope, $state) {
        $scope.navTitle = 'Entry Page';

        $scope.signIn = function () {
            $state.go('main.home');
        }
    }
})();

In Angular, you declare your app with an array of dependencies:

angular.module('ionicApp', ['ionic'])

and you reference it only by name:

angular.module('ionicApp')

Answer №2

Is it necessary for the Controller definition to be placed above the module definition?

(function () {
    'use strict';

    // Start by defining the Controller
    function EntryPageController($scope, $state) {
        $scope.navTitle = 'Entry Page';

        $scope.signIn = function () {
            $state.go('main.home');
        }
    }

    // Then include it in the module
    angular.module('ionicApp', ['ionic'])
        .controller('EntryPageController', ['$scope', '$state',    EntryPageController]);

})(this);

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

Step-by-step guide on creating a unique Bootstrap Nav overlay effect

My Bootstrap navigation bar is functioning properly However, I am facing an issue in adding an overlay to the NAV menu on mobile screens I am using Bootstrap and Umbraco 7 <nav class="navbar navbar-fixed-top navbar-default" role="naviga ...

Locate all inputs containing a special attribute name, wherein a portion of the name corresponds to a JavaScript variable

$("td[id^='td' + myvar + '_']") Can someone help me with a solution to substitute the static value of 0 in this code snippet with the dynamic variable myvar? Thanks! ...

Having a quandary with Socket.io when using clients.length (where clients refers to io.sockets.clients();)

Typically, when sending JSON from one client to another, everything works smoothly. However, if there is only one client, packets are still being sent. To address this issue (on the server-side in node.js), I implemented the following solution: var client ...

JavaScript: inscribe in a specific cell

I have a table cell within a div element and I am trying to display the date for the last Thursday in it: <body> <div> <table id="TableName" width="auto"> <thead> <tr> ... ...

Retrieve the height of a div element in an AngularJS framework, and assign this value to a corresponding attribute of another element

Is it possible to retrieve the height of an element using AngularJS and assign it to another div's attribute? In my Bootstrap website, I have a fixed sidebar that needs to stop before reaching the footer. To achieve this, I currently have to manually ...

Ways to divide a fixed angular variable into individual variables

Currently, I am working on a code that requires me to integrate an inputted dimension as the width and height of the displayed image. The specified dimension format is 300x250, and the image's height and width should adjust accordingly. The piece of ...

Is there a way to replace the message 'no rows to show' with a custom component in ag-Grid for react?

Currently, I am utilizing ag-grid in my React application https://www.ag-grid.com. When the table or grid is empty, it displays the default message "No rows to show." However, I am interested in customizing this message or possibly incorporating a custom ...

Incorporating navigation controls into a modal window

I have successfully created a sign-in modal, but now I'm looking to include buttons at the top. One button should redirect users to register/sign up, and the other button should lead them back to the sign-in modal, as shown in the image I've link ...

Divide a single array into two separate arrays using React Native

My goal is to divide an array into two separate arrays, one for letters and the other for frequencies. var list = [ "ES 324798", "LE 237076", "EN 231193" ] This is the original array that needs to be split. I am looking to create an array with all the l ...

The bootstrap navbar dropdown feature isn't functioning properly on iPhones

Currently utilizing "bootstrap": "~3.3.4" within the mean.js framework, I am facing an issue with the navbar dropdown menu. On desktop, everything functions as expected - the dropdown opens and remains open when the icon is clicked. However, once deployed ...

Implement Placeholder feature in ng2-ckeditor with the combination of Typescript and Angular 2.0

I am encountering an issue while trying to add the placeholder plugin to the CKEditor toolbar. When I include extraPlugins:'placeholder' in the CKEditor configuration, I receive the following error - Error: [CKEDITOR.resourceManager.load] Resou ...

Please input new items by clicking a button

I have a dilemma with handling an array of objects in my Vue component. I am using v-for to display the objects, but now I want to update certain items in the array and save only those changes in a new object. Currently, when I attempt this by mapping over ...

What are some creative ways to customize the background of a full component?

Is there a way to modify the background color of an entire component? I want the color to cover the full width and height of the component. I attempted using the body tag, but it was ineffective. Do I need to enclose all components in a div and then appl ...

Unable to display results in React Native due to FlatList not being shown

I'm a beginner to React Native and I'm attempting to create a simple flatlist populated from an API at , but unfortunately, no results are displaying. Here's my App.tsx code: import React from 'react'; import type {PropsWithChildre ...

Counting records in a nested ng-repeat using AngularJS

As a newcomer to AngularJS, I am facing an issue with a nested ng-repeat using a custom filter. I want to display the record count of Orders being shown, but when applying a product filter, it does not work as expected. For instance, if an order has no pro ...

Encountering a 403 Forbidden error when attempting to include a full URL in my JSON data using jQuery and PHP

I am currently working on a project to create a card generator for educational purposes and to have some fun. I am learning how to gather data from user inputs and save it to a database. However, I encountered an issue when trying to send a simple JSON da ...

Toggle the visibility of a div using JavaScript depending on the data value

I have a collection of images displayed in div tags with data attributes. My goal is to toggle their visibility using CSS based on a match with input text. I iterate through the divs with the matching class, then loop through the words in the input array, ...

Mobile devices have a fixed distance and center alignment on the horizontal timeline

I am attempting to create a horizontal timeline similar to this example: https://codepen.io/ritz078/pen/LGRWjE The issue I am facing is that I do not have specific dates (DD/MM/YYYY) but only ranges such as 1998-2002 or single years like 2009. This has ca ...

Why is there an issue with the JavaScript array when accessing data['sax']?

There seems to be some confusion regarding the contents of this array and how it assigns values to the variable set. It would be greatly appreciated if someone could provide an example pertaining to the usage of data['sax']. Additionally, an expl ...

Is it possible for me to generate HTML using JavaScript?

Below is the javascript code I have written, saved as create.js: var stuff = document.querySelector(".stuff"); var item = document.createElement('div'); item.className = 'item'; stuff.appendChild(item); This is the corresponding HT ...