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. Currently, this is what my setup looks like:

app.js

var app = angular.module('app', ['ngRoute']);
app.run(function () {});
app.config(function ($routeProvider, $locationProvider) {
    $routeProvider.when('/', {
        templateUrl: 'js/templates/login.html',
        controller: 'LoginController'
    });
});

Login Controller

angular.module('app')

    .controller('LoginController', function ($scope) {
        this.title='toto';
        this.data = {};
        this.submit = function () {
            console.log(this.data);
        };
    });

Admin View

<!doctype html>
<html lang="en">
    <head>
        <title>Blog Administration</title>
        <!--css-->
        <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"/>

        <!--js-->
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

        <!--angular-->
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular-route.js"></script>
        <script src="js/app.js"></script>
        <script src="js/controllers/loginController.js"></script>
    </head>
    <body ng-app="app">
        <div id="wrapper">
            <div class="container" id="view" ng-view>

            </div>
        </div>
    </body>
</html>

Login Template

<!DOCTYPE html>
<html>
  <head lang="en">
    <meta charset="UTF-8">
    <title></title>
  </head>
  <body ng-controller="LoginController as login">
    <div class="container">
      <div id="login" class="col-md-4 col-md-offset-4">
        <div id="login-form">
          <h4>{{ login.title }}</h4>

          <form ng-submit="login.submit()"><!--username-->
            <div class="form-group">
              <input id="username" type="text" ng-model="login.data.username"/>
            </div>
            <!--password-->
            <div class="form-group">
              <input id="password" type="password" ng-model="login.data.password"/>
            </div>
            <!--submit-->
            <div class="form-group">
              <button class="btn btn-primary" type="submit">Login</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </body>
</html>

The main issue I am facing is that nothing is being rendered. Is it feasible to utilize a controller per template?

When placing the

<ng-controller="LoginController as login">
directive in the view body rather than the template, everything renders perfectly.

Is it considered best practice to define a controller for each template? I believe the login template should remain as generic as possible for potential use in various views if the user isn't authenticated. Therefore, I question whether placing the login() action within the controller managing the Admin view is incorrect.

I would greatly appreciate any insights on the optimal practices to implement in this scenario.

Answer №1

If you want to implement the controllerAs syntax with routeProvider, make sure to add an additional property in your route configuration:

$routeProvider.when('/', {
    templateUrl: 'js/templates/login.html',
    controller: 'LoginController',
    controllerAs: 'login'
});

After that, clean up your login template by removing everything except the actual template content. This means no HTML, body tags, etc. Also, there is no need for an extra ngController directive in the partial template:

<div id="login" class="col-md-4 col-md-offset-4">
    <div id="login-form">
        <h4>{{ login.title }}</h4>

        <form ng-submit="login.submit()">
            <!--username-->
            <div class="form-group">
                <input id="username" type="text" ng-model="login.data.username" />
            </div>
            <!--password-->
            <div class="form-group">
                <input id="password" type="password" ng-model="login.data.password" />
            </div>
            <!--submit-->
            <div class="form-group">
                <button class="btn btn-primary" type="submit">Login</button>
            </div>
        </form>
    </div>
</div>

Answer №2

 Query 1: Can a controller be assigned to each template individually?
 A: Absolutely! It's quite straightforward. The next explanation will show you how.

 Query 2: Is it recommended to assign a controller to each template?
 A: According to AngularJS guidelines, it is considered a best practice. Let's explore two different approaches to defining the controller for a template:

a. Embedding the controller directly into the template like so: <div ng-controller="myCtrl">The entire template content resides within this div.</div>

b. Specifying the controller in the app.js file when loading the template as shown below:

        .state('app.products.all', {
            url: '/all',
            templateUrl: 'tpl/products/blocks/thumb.html',
            controller: 'ProductsAllCtrl'
        })

 In this example, the controller is linked with the template path. The second method proves to be more efficient than the first.

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

Issue encountered with the Selenium JavaScript Chrome WebDriver

When it comes to testing an application, I always rely on using Selenium chromewebdriver. For beginners like me, the starting point was following this insightful Tutorial: https://code.google.com/p/selenium/wiki/WebDriverJs#Getting_Started After download ...

How to extract only the truthy keys from an object using Angular.js

I am looking to retrieve only the keys with a true value in the data object and display them in the console with the specified format: Object { Agent=true, Analytics / Business Intelligence=true, Architecture / Interior Design=false } The catego ...

Having trouble reaching a public method within an object passed to the @Input field of an Angular component

My configurator object declaration is as follows. export class Config { constructor(public index: number, public junk: string[] = []) { } public count() : number { return this.junk.length; } } After declaring it, I pass it into the input decorated fi ...

Why is it that injecting javascript within innerHTML seems to work in this case?

According to the discussion on this thread, it is generally believed that injecting javascript in innerHTML is not supposed to function as expected. However, there are instances where this unconventional method seems to work: <BR> Below is an examp ...

Guide on retrieving a nested JSON array to extract a comprehensive list of values from every parameter within every object

A JSON file with various data points is available: { "success": true, "dataPoints": [{ "count_id": 4, "avg_temperature": 2817, "startTime": "00:00:00", "endTime": "00:19:59.999" }, ... I am trying to extract all the values of & ...

Unable to access .root in the unmounted test renderer while performing React Native unit testing

Hello, I am currently in the process of testing my app using react-native-testing-library. Unfortunately, when I run the test, it fails. I'm encountering an error that says: Can't access .root on unmounted test renderer There appears to be a ...

Checking the minimum and maximum character limits in the md-text-float

Is there a way to verify that a user is inputting text between 4-20 characters in length into an md-text-float element (an angular material directive)? Typically, with plain Angular, one would use the ng-minlength and ng-maxlength attributes within an inpu ...

Error message received from Express middleware: "Unable to modify headers after they have been sent."

I have created middleware for my Node Express app to perform the following tasks: Checking all incoming requests to determine if they are from a bot Allowing requests for raw resources to proceed Serving an HTML snapshot if the request is from a bot How ...

Using an AJAX function to retrieve data from two different server-side scripts and populate two separate HTML elements on the page

My goal in this coding situation is to change values in multiple DOM targets. The example from Tizag shows the DOM being altered within the onreadystatechange function, like this: if(ajaxRequest.readyState == 4){ document.myForm.time.value = ajaxRequ ...

React-NextJS encountered an error: TypeError, it cannot read the property 'taste' because it is undefined

Recently, I've been encountering an issue with NextJS that keeps throwing the error message: TypeError: Cannot read property 'taste' of undefined. It's quite frustrating as sometimes it displays the expected output but most of the time ...

What is the best way to embed two controllers within an AngularJS webpage?

Currently, I have a Web Forms ASP.NET website that I am trying to enhance by adding an AngularJS page. This page is meant to interact with my RESTful Web API to display quotes for selected securities upon button click. While the Web API calls work when dir ...

The onclick event for a Bootstrap .btn-group checkbox functions correctly in JSFiddle, but encounters issues when tested

The toggle button group in the form below utilizes Bootstrap and checkboxes. I am looking to track click events on the checkbox inputs. <html> <head> <title>Example: Bootstrap toggle button group</title> <meta charset="UTF-8 ...

Performing addition and subtraction calculations with HTML and Javascript

I need help creating a simple HTML table for adding and subtracting values, with a limit of 10 and a minimum of 0. I have two functions set up, additionalAdd and additionalSub, triggered by the onclick event, but I keep getting an error saying that totalAd ...

Execute a Python script using an Ajax jQuery call

Recently, I encountered an issue when attempting to execute a python file via jQuery. To address this problem, I conducted research online and came across a specific code snippet designed to call and run a python script. Below is the AJAX code utilized fo ...

Guide on accessing oversized items (such as response objects) that are too immense for the command-line interface

Currently delving into coding and learning NodeJS, one aspect that keeps tripping me up is understanding the response object. It's quite comprehensive, and I find myself overwhelmed when trying to analyze all the data it outputs through console.log() ...

What is the best way to retrieve a value by using the data.get() method?

I am currently facing an issue with retrieving the value of a textarea that I have dynamically added to a fieldset in my form. When I attempt to submit the form, the code below is executed: function handleSubmit(e) { e.preventDefault(); console.log( ...

The $route object in Vue is not configured

Currently, I am delving into the realm of Vue router and aiming to achieve programmatic navigation without relying on <router-link> in my templates file. Here is a glimpse of my router and view setup: router = new VueRouter({ routes: [ ...

The JQuery functionality is failing to execute properly on Internet Explorer

I have developed a JQuery script that appears to be working perfectly in all browsers, except for IE 8. Interestingly, when I checked Internet Explorer's error details, it did not provide any specific information about the issue. Instead, IE simply po ...

The array filtering functionality is not functioning as intended

Struggling with correctly filtering data in JavaScript. Here's an example where var1 = 20, var2 = 10, var3 = 30, var4 = 40. This is the code snippet: var variables = ['var1', 'var2', 'var3', 'var4'], values = [ ...

Fill input text fields with values based on dropdown selection and start with 2 input fields pre-filled

Initially, the issue is that there are 2 input text fields displayed. Depending on the selection from a drop-down menu ranging from 2 to 6, additional input fields should be added or removed. Here's my code: function addElements(selectElement) { va ...