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

Javascript Object and Conditional Statement

I am working on a Dygraph object creation script that includes a data variable. However, I want to avoid passing in this variable for older browsers. Here is the code snippet: function prime() { g = new Dygraph( document.getElementById("g"), d ...

Extract data from a website with Python and selenium

I need to scrape the data from a table that seems to be generated in JavaScript. I'm using selenium and Python3 for this task. While looking at how others have approached similar challenges, I noticed they use xpath to locate the tables before scrapin ...

Ways to determine the total number of npm packages installed, excluding development dependencies

Is there a specific NPM command I can run from the CLI to count only the installed NPM Modules in my package that are not Dev Dependencies? When I use npm ls, it lists all packages without distinguishing between regular dependencies and DevDependencies. ...

Prevent random files from being included in RequireJS's r.js optimization process and instead load them asynchronously

Currently, I have successfully implemented RequireJS and a Grunt-based build process that optimizes my JS app into one file using r.js. This consolidation of all app files has proven to be efficient for production deployment. However, the issue arises wit ...

How to properly handle sending an empty post request in Angular 2

My current issue revolves around attempting to send data from my application to the server using a POST request, however, the server seems to be receiving empty POST data. This is the function responsible for sending the data: private headers = new Heade ...

What is the best way to enhance a React Native component's properties with Flow?

I'm currently working with Flow version 0.54.1 in my React Native project, specifically using version 0.48.3. I have developed a component named PrimaryButton that acts as a wrapper for the native TouchableOpacity component. My goal is to define custo ...

What is the best way to loop through an array inside an object stored within another array using *ngFor in Angular 2?

Overview: My game data is structured as an array called 'game' with seven objects representing each round. Each round object contains details like 'roundNumber', 'title', 'players', and 'winner'. The &apos ...

What could be causing my images not to show up when I use string interpolation for src links in Vue.js?

I've encountered an issue while working on Vue.js where I'm struggling to render a couple of images from the local directory. What puzzles me is that this problem arises when using string interpolation, like in the code snippet below: <img :s ...

Determine the moment when jQuery's load() function completes the loading of several images

My script utilizes jQuery's getScript() function to dynamically retrieve blog posts from Tumblr accounts. The response from the script is a JSON structure called tumblr_api_read, which includes image URLs among other things. function read(blogName) ...

What is preventing Javascript from executing a function when there is an error in another function?

Can you explain why a JavaScript function fails to run if there is an error in another function? Recently, I encountered an issue on my HTML page where the alert from the popup1() function would not load. It turns out the problem stemmed from an error in ...

Is it possible to switch the summernote editor between airmode and toolbar mode?

Currently, I am working on creating a report editor that displays only one toolbar when multiple summernote WYSIWYG editor sections are used. My solution involves having the first section as a full editor and the other section in airmode. Below is the HTM ...

Unable to locate $element post minification

I've encountered a peculiar bug that only seems to manifest when my web application is running in Karaf, but not on the webpack-dev-server. Whenever I open a dialog while the web app is running in Karaf, I receive this error in the browser console: a ...

Utilizing the child element's attribute value in a list to dynamically modify the CSS styling of a div element

I'm struggling with designing a ranking bar that consists of 9 bars. I want the height of the bars to vary, with bar 0 and bar 8 being the longest. However, I am having difficulty manipulating my jQuery selector to change the CSS style of the bars bas ...

Determining the width of an element in Chrome using jQuery

Before adding an element to the body, I require its width. The code below functions correctly in Firefox, however it does not work properly in Google Chrome. <style> .testDiv { width:150px; height:100px; } </style> <script> var di ...

Create a URL hyperlink using javascript

I am looking to create a link to a page that updates its URL daily. The main URL is where X represents the day of the month. For example, for today, July 20th, the link should read: In my JavaScript section, I currently have code that retrieves the cur ...

leveraging the phonegap plugin with AngularJS application

Currently, I am integrating AngularJS with a custom Cordova plugin that exports an object called deviceAttributes containing various methods. Do I need to make any adjustments in my JavaScript code to access the methods of this object? The console output s ...

Creating a functional hyperlink within a ui-sref element in Ionic

I'm struggling with a simple code snippet in Ionic 1. It basically shows a list of items that are clickable to navigate to a details page. However, I want to add functionality so that when clicking on the phone icon next to each item, it will initiate ...

Creating protected routes in ReactJs using Typescript by utilizing a Higher Order Component (HOC) as

I'm struggling to create a basic HOC that can protect a component, ensuring that the user is logged in before rendering the component. Below is my attempt at building the protective HOC (not functional yet). export default function ProtectedRoute(Com ...

Utilizing AngularJS for a Simple AJAX GET Request

I'm currently developing a Chrome extension with Angular JS. My goal is to retrieve and parse an HTML page from a third-party website. When using Angular JS $resource to achieve this (is there a more effective method?), I encountered an unusual objec ...

Split a string in Javascript and store the resulting parts in two separate variables

After an extensive search, I haven't come across any informative posts regarding my specific inquiry. I'm currently dealing with a variable that holds a string and my objective is to split it into two separate variables. Consider this example: ...