Using AngularJS to invoke the ng-required directive and trigger a function

Is it possible to make the required value dependent on a function? Something similar to this? I need to achieve this in order to dynamically change the required attribute for form inputs...

HTML:

Name: <input type="text" ng-model="user.name"  ng-required="isRequired('name')" />
Age: <input type="text" ng-model="user.age"  ng-required="isRequired('age')" />

JS:

$scope.isRequired(fieldName){
         $scope.requiredFields = [];
         //$scope.requiredFields = DATA FROM A REST API
        for (i in requiredFields) {
           if (requiredFields[i] == fieldName){
                return true;
           }
        }
        return false;
    }

Answer №1

Alternative Solution: After reviewing your updated question, it seems that achieving what you want is possible. The issue with your initial approach is that ng-required cannot execute a function, as it only reads a boolean value. However, we can create variables dynamically based on data from the server to automatically set fields as required:

Updated Plunker

<form>
  Name: <input type="text" ng-model="user.test" ng-required="name" /><br/>
  <input type="text" ng-model="user.name" ng-required="age" />
  <br/>
  <button type="submit">Submit</button>
</form>

I introduced a $scope property for each input in the ng-required attribute. By dynamically creating this $scope property and setting it to true according to our data, we can achieve the desired functionality:

$scope.isRequired = function(){
         $scope.requiredFields = [];
         $http.get('fields.json')
         .success(function(data){
           $scope.requiredFields = angular.fromJson(data);
            console.log($scope.requiredFields.required)
           for (i = 0; i < $scope.requiredFields.required.length; i++) {
           $scope[$scope.requiredFields.required[i]] = true
            }
            console.log($scope[$scope.requiredFields.required[0]]);
         })

         //$scope.requiredFields = STUFF FROM SOME REST SERVICE

    }
    $scope.isRequired()

This script iterates over an array of required fields from the server, dynamically creating a $scope property for each required field and setting it to true. Any input with this $scope property in its ng-required will now be mandatory. Inputs without this dynamic property will not trigger the ng-required logic.


Original solution:

Plunker

As mentioned earlier, ng-required only accepts a Boolean value, but we can toggle this value using a function.

HTML

<form>
  Name: <input type="text" ng-model="user.name" ng-required="isRequired" />
  <br><button ng-click="toggle()">Required: {{isRequired}}</button>
  <button type="submit">Submit</button>
</form>

JS code:

$scope.isRequired = true;
$scope.toggle = function() {
  $scope.isRequired = !$scope.isRequired;
}

Answer №2

Although this information may be a few years old and AngularJS may have evolved, the current accepted answer is not accurate. It is possible to easily run a function within ng-required, as it accepts an expression, which can include a function. For instance:

index.html

<div ng-controller="ExampleController" class="expressions">
  Expression:
  <input type='text' ng-model="expr" size="80"/>
  <button ng-click="addExp(expr)">Evaluate</button>
  <ul>
   <li ng-repeat="expr in exprs track by $index">
     [ <a href="" ng-click="removeExp($index)">X</a> ]
     <code>{{expr}}</code> => <span ng-bind="$parent.$eval(expr)"></span>
    </li>
  </ul>
</div>

script.js

angular.module('expressionExample', [])
.controller('ExampleController', ['$scope', function($scope) {
  var exprs = $scope.exprs = [];
  $scope.expr = '3*10|currency';
  $scope.addExp = function(expr) {
    exprs.push(expr);
  };

  $scope.removeExp = function(index) {
    exprs.splice(index, 1);
  };
}]);

In script.js, the function addExp is declared and included in the scope, then it's executed in the ng-click directive of the a tag, which also permits an expression as its parameter.

This code snippet is sourced directly from the AngularJS documentation on expressions. While it doesn't specifically use ng-require, any directive that allows an expression will function in the same way. The syntax used for ng-require here mirrors that of using a function.

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

Encountering a display issue within a port using Express

Recently, I enrolled in an advanced ExpressJS course. While exploring the course website, I stumbled upon the "hello world" section. Intrigued, I decided to copy and paste the code provided below: const express = require('express') const app = ex ...

Updating the footer of a React application using Material UI Grid

Having some trouble customizing the footer in a React Material-UI grid. Refer to the image below for details. Any ideas on how to change the: 1 row selected? Thank you! ...

Resolving TypeError: matchesSelector method is not recognized within React component

I am currently integrating masonry-layout from the official website to create a masonry grid within my component. However, I encountered an issue where clicking on a rendered element triggers the error message TypeError: matchesSelector is not a function. ...

Why does AngularJS $watch only execute once?

Why do the codes in the watch only run once? How can I address this issue? this.$rootScope.$watch('tabType', () => { if (this.$rootScope["tabType"] === TabType.Sent) { this.$scope.refreshSentList(); } else if (this.$rootScope[ ...

Exploring the possibilities of using AngularJS for AJAX functionality in a Ruby On Rails

I recently started learning AngularJS and Rails, and I attempted to develop a Rails application incorporating AngularJS. Currently, I am looking to make a POST request to send data and insert it into the database. In the Activity Controller: def create ...

Struggling with Responsiveness: Challenges with Detailed Information and Image Grid Design

Encountering challenges in achieving the desired responsiveness for a grid layout consisting of details and an image. The layout displays correctly on desktop screens, with details on the left and the image on the right. However, on mobile screens, the ima ...

Having trouble retrieving the ng-model value from input in the controller

I am new to Angularjs and I am working with a datepicker in Ionic. After selecting a date, the input field is correctly getting the value of the selected date. However, I am facing an issue when trying to access this value in the Controller using $scope. ...

The type 'Observable<any>' cannot be assigned to the type 'Observable<T>'

Here is the code I am working with: import {HttpClient} from '@ngular/common/http'; private httpClient: HttpClient; do_request(method: string, url: string, ...

Javascript Callback function not working as expected

I'm attempting to include an anonymous callback function in my code. I know it might seem a bit messy. By typing into the intro section, it triggers the animation using the .typed method with specific parameters. What I'm struggling to do is imp ...

The equivalent of the $.curCSS method in jQuery version 1.10 is as follows:

While working with a library called mcdropdown from http://www.givainc.com/labs/, I encountered an issue with the $.curCSS method. The latest version of jQuery no longer supports this method and suggests using $().css instead. Following the documentation, ...

Using a Javascript method to access a sibling property within an object

Is there a way to access a sibling property from a method in JavaScript? This seemingly simple task has proven challenging for me. Take a look at the sample code below. let f = { a: 3, printMyBrother() { console.log(X) } }.printMyBrother f() ...

Speed up - Handle alias resolution with module federation

Currently import federation from '@originjs/vite-plugin-federation'; import react from '@vitejs/plugin-react-swc'; import dns from 'dns'; import path from 'path'; import { visualizer } from 'rollup-plugin-visual ...

Unable to retrieve component name using React.Children

While working with react in the nextjs framework, I attempted to create my own dropdown component structured as follows: <Dropdown> <DropdownToggle>Action</DropdownToggle> <DropdownMenu> <DropdownItem>Menu 1</Dr ...

Unable to associate Interface with HTTP response

When I run the following code in Chrome console, I get an error: ERROR TypeError: t.json(...).map is not a function. However, both ng serve -prod and ng test --sm=false work fine. My goal is to map the result to the model in Interface and display it in HT ...

Modifying the value of an animated status bar using the same class but different section

I need the status bars to work individually for each one. It would be great if the buttons also worked accordingly. I have been trying to access the value of "data-bar" without success (the script is able to process the "data-max"). However, the script see ...

Best Placement for Socket.io Server in WebStorm Express Template

Trying to integrate socket.io into an express server generated by WebStorm. Should the setup of the server and socket.on events all be placed inside /bin/www, or is it better practice to create separate controllers like index and users pages? PS: Another ...

Send an ajax request to upload several images to the server

I am currently facing an issue with my web application that allows users to create posts with a maximum of 15 images. I have implemented AJAX requests to send all the data, including the images, in one request. However, I encountered this error: An error ...

Separate the information into different sets in JavaScript when there are more than two elements

Upon extraction, I have obtained the following data: ╔════╦══════════════╦ ║ id ║ group_concat ║ ╠════╬══════════════╬ ║ 2 ║ a ║ ║ 3 ║ a,a ...

Unable to import local npm package due to an error

We are in the process of migrating multiple websites, each with its own project, to Vue.js. As we transfer files over and bundle them using Webpack, we have encountered a need to consolidate similar components and core JavaScript files into a shared librar ...

Using the html5 file reader API in JavaScript to retrieve a file as a binary string and then sending it through an ajax request

I'm attempting to obtain the binary string of files, but I seem to be unable to do so. Why does readAsDataUrl work while readAsBinaryString doesn't? I have posted my code on jsbin and any help would be greatly appreciated. Thank you. Check out ...