What methods can a controller use to verify the legitimacy of the scope?

I'm a bit perplexed when it comes to validation in angular. It seems like all of the validation is connected to the form. But what happens when the controller needs to ascertain if the model is valid or not?

Here's an example I quickly whipped up:

HTML

<div  ng-app="stpApp">
<div id="multiStop" class="fullBottomContent" ng-controller="multiStopController">
<ul class="journey">
        <li ng-repeat="journey in inboundJourney">
            <ng-form name="journeyForm">
                <span>
                    <input type="text" class="AirportName" name="DepartureAirport" ng-model="journey.DepartureAirport" ng-required="true" />
                    <span ng-show="journeyForm.DepartureAirport.$error.required">Invalid</span>
            </ng-form>
            <a class="removeJourney" ng-click="removeInboundJourney($index)" href="javascript:void(0)">Remove</a>
        </li>
    </ul>
    <span ng-show="valid()">this is all valid</span>
    <span ng-click="addInboundJourney()" title="Add a journey">+</span>
</div>
</div>

JavaScript

var stpApp = angular.module('stpApp', []);

stpApp.controller('multiStopController', function ($scope, $compile, $http) {

    $scope.showAddButton = true;
    $scope.dataLoaded = false;
    $scope.inboundJourney = [
    { 'DepartureAirport': '',
        'DestinationAirport': '',
        'DepartureDate': '',
        'DepartureTime': '9',
        'Class': 'All'
    },
        { 'DepartureAirport': 'Test1',
        'DestinationAirport': '',
        'DepartureDate': '',
        'DepartureTime': '9',
        'Class': 'All'
    }
  ];

    $scope.valid = function() {
     //how can I check for validity here? 
        return true;
    }
    $scope.addInboundJourney = function () {
        $scope.inboundJourney.push({ 'DepartureAirport': '',
            'DestinationAirport': '',
            'DepartureDate': '',
            'DepartureTime': 9,
            'Class': ''
        });
    }

    $scope.removeInboundJourney = function (index) {
        $scope.inboundJourney.splice(index, 1);
    }
});

Link to Fiddle

My challenge lies in getting the valid() function to accurately determine whether the data in the model is valid or not. I've attempted using journeyForm.$valid, $scope.journeyForm.$valid, and

$scope.journeyFormDepartureAirport.$valid
, but none seem to work.

I'm struggling to figure out how to access $valid from within my controller. Particularly since there are a variable number of forms.

Is it appropriate for the controller to have knowledge of the forms? Isn't that more of a view concern?

It appears that all the validation is concentrated within the view, leading me to believe that angular lacks the concept of an invalid model. It simply sees the data as just that. However, this poses a problem for me as I need to ensure that the model meets all criteria specified in the view, such as ng-required, prior to executing an action in the controller.

Answer №1

To provide a clearer explanation regarding the usage of $valid

<form name="myform" >
<input type="text" name="input1" ng-required="true"/>

 ....

JavaScript Code:

$scope.valid = function() {
        return $scope.myform.$valid; /* how to retrieve $valid for 'myform' form */
    }

Answer №2

Is it possible to utilize a $watch function?

$scope.valid = false;

$scope.$watch('inboundJourney', function(){
    var isValid = false;
    //determine if inboundJourney is valid
    $scope.valid = isValid;
});

Next, use it as the condition for showing content

<span ng-show="valid">this content is valid</span>

Answer №3

With Rob's assistance, I was able to solve the issue I was having. It turned out that the placement of the form was causing a problem:

<li ng-repeat="journey in inboundJourney">
     <ng-form name="journeyForm">

It seems Angular did not like having the form inside the ng-repeat. To resolve this, I moved the form outside of the loop:

<ng-form name="journeyForm">
     <ul class="journey">
        <li ng-repeat="journey in inboundJourney">

After making this adjustment and following Rob's suggestion,

$scope.valid = function() {
    return $scope.journeyForm.$valid; /* ensuring 'journeyForm' is valid */
}

everything started working as intended.

View Fiddle


I must admit, it was frustrating that there were no warnings about the incorrect syntax. In my limited experience with Angular, this lack of error messages can be quite challenging. More error messages would be appreciated!

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

I am encountering difficulties with generating images on canvas within an Angular environment

I am trying to crop a part of a video that is being played after the user clicks on it. However, I am encountering the following error: ERROR DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may no ...

Stopping JavaScript when scrolling to the top and running it only when not at the top

I found a great jQuery plugin for rotating quotes: http://tympanus.net/codrops/2013/03/29/quotes-rotator/ Check out this JSFiddle example: http://jsfiddle.net/LmuR7/ Here are my custom settings (with additional options that I haven't figured out yet) ...

Refresh the data list displayed within a specified div container

On my jsp page, I initially populate a model attribute with some data. Then, I use the following code to display this list on the jsp page: <c:forEach var="pattern" items="${patterns}"> <li class="list-group-item liitem"><st ...

Exploring the possibilities of toggling between a personalized CSS design and a Bootstrap CSS layout

Is it possible to implement a dropdown menu on my sample-page using javascript/jquery in order to switch between a custom layout and a bootstrap layout? ...

Having trouble deciphering mathematical formulas while editing content on ckeditor

While using math formulas in CKEditor, I noticed that when I insert new content via textarea, the formulas are displayed correctly. However, when I go back to edit the content, the text formulas do not display as before. This is the source code I am using ...

What are the steps to add 8 columns to the second row in my table?

this is an example of HTML code that showcases a table structure with multiple rows and columns. You can view the full code snippet here. The table includes different sections, such as section1, section2, section3, and section4 in the first row (tr). In t ...

Invoking a JavaScript function within a different JavaScript function

Is there a way to ensure that the JavaScript function works properly even when using a text editor? var editor = $('#CKEditor1').ckeditorGet(); editor.on("instanceReady", function () { this.document.on("keydown", function (event) { ...

Adding Bootstrap modal content to a webpage before it renders is a simple process that involves preloading the

When using Bootstrap modal, is it possible to load a remote URL along with the parent page without needing to click on a button? ...

Using canvas transformation changes the way drawImage is applied

I have been working on a game as a hobby and you can find it at . I have managed to get most aspects of the game working well, such as transformation, selection, movement, and objects. However, there is one particular challenge that I am struggling with. ...

Looking to divide a multiple-page .TIFF document into several PNG or JPG files using the sharp module in node.js?

Is there a way to split a single .tiff file with multiple pages into several .png or .jpg files without using ImageMagick or GraphicsMagick due to limitations in my codebase? I am unable to install CLI tools so I'm exploring alternate solutions. I kn ...

Leveraging onClick in combination with React's AutoBind

Just started learning React, so please point me towards documentation if I missed anything. I'm attempting to initiate an Ajax call using the onClick method following a tutorial on React. See the code snippet below. doSomething: function() { // ...

locomotory mesh decentralized sorting

I am attempting to implement in-browser sorting for my flexigrid. Currently, the grid is displaying data from a static XML file exactly how I want it, but the table itself does not sort because it is working off of local data. While researching solutions, ...

Retrieving multiple selected row values using an ASP Repeater

Within my repeater, I have three values bound: a visible "User Name" column, a visible "Business" column, and a hidden field called "UserId". My goal is to implement the following functionality: when a row is clicked, it should highlight in a different c ...

Testing the functionality of a service using unit tests that involve a promise

I have developed a service for a current project and now I am working on writing a unit test for it. Below is the code snippet for the service: angular.module('services').factory('Authorization', ['$q', 'Refs', func ...

Exports for Express Router Module/Functions

I am currently working on exporting a function and an express router from the same file. The function is intended to verify certificates, while the route is meant to be mounted on my main class for other routes to use. I want to encapsulate both functional ...

In order to ensure JavaScript can be universally applied to all images, it needs to be made more generic

I have developed JavaScript functions to enable zoom in and zoom out functionality for an image through pinching gestures. Now, I aim to refactor the code below so that I can include it in a shared JavaScript file. var scale = 1; var newScale; ...

Viewing HTML web pages using Mozilla Firebox

Printing an HTML table with lots of content has been a challenge for me. Google Chrome didn't work, so I switched to Mozilla Firefox. However, now Firefox is breaking the page inside the table. My question is how can I trigger print preview in Firefox ...

Modifying the src attribute of an object tag on click: A step-by

So I have an embedded video that I want to dynamically change when clicked on. However, my attempt at doing this using JavaScript doesn't seem to be working. <object id ="video" data="immagini/trailer.png" onclick="trailer()"></object> H ...

Step-by-step guide on implementing virtual scroll feature with ngFor Directive in Ionic 2

I am working on a project where I need to repeat a card multiple times using ngFor. Since the number of cards will vary each time the page loads, I want to use virtual scrolling to handle any potential overflow. However, I have been struggling to get it ...

The tab component is failing to load due to an issue with the Bootstrap tab

I've created a page displaying different locations with two tabs - one for Google Maps and another for weather. For example, take a look at this location: The issue I'm facing is that when switching between the tabs, they don't load fully. ...