Using Angular.js to disable a button based on a substring in an object array

Within my project, there are various tasks to be completed. If a user enters a todo item containing the substring clean, such as cleaning, clean, or cleaner, the input should be disabled.

To achieve this in my Angular controller, I have created a method that checks for the presence of the substrings and disables the input accordingly.

$scope.disableInput = function (todos) {
    todos.forEach(function (item) {

        if (item.toLowerCase().indexOf('clean') > -1) {

            return true;
        } else {

            return false;
        }
    });
};

In my HTML file, I have included the ng-disabled attribute in the input field.

    <form ng-submit="addTodo();">
        <input type="text" ng-model="todoText" ng-disabled="disableInput(todos)">
        <input type="submit" value="add">
    </form>

Manually setting the value to true works, but the input does not respond to the return value of the disableInput method. I aim to dynamically check the todos object each time a new item is added and disable the input based on the substring.

How can I ensure that the true value returned by the disableInput method reflects back to the template, resulting in the input being disabled?

You can view the JSFiddle version here.

This example was inspired by this source, with the addition of the disable functionality.

Answer №1

When looking at your function (below), you are going through a collection and returning a boolean value for the first object. This should definitely catch your attention.

$scope.disableInput = function (todos) {
todos.forEach(function (item) {

    if (item.toLowerCase().indexOf('clean') > -1) {

        return true;
    } else {

        return false;
    }
});

};

'I needed to verify the todos object each time a new item is added'

The logical place to perform this check would be within the function that runs when adding a todo.

Instead of iterating over all todos, we can simplify it like this:

var disableInput = function (input) {
    if(input.toLowerCase().indexOf('clean') > -1){
        return true;
    }
    return false;
};

To keep track of whether the input is disabled, you can add a variable to the scope.

$scope.disabled;

In your addTodo function (excerpted from your fiddle), include the 'clean' string check on the newly entered text.

 $scope.addTodo = function() {
    $scope.todos.push({
       text:$scope.todoText,
       done:false
     });

     //Assign the result of the above function to the scoped variable 
     $scope.disabled = disableInput($scope.todoText);

     $scope.todoText = '';
  };

Lastly, in your HTML code, bind the disabled variable to ng-disabled attribute.

<input type="text" ng-model="todoText"  size="30"
 placeholder="add new todo here" ng-disabled="disabled">

Check out the revised fiddle I used for testing purposes.

jsFiddle

I hope this explanation proves helpful

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

The <h> tag gains height on its own accord

Here is my original code: <h4 class="orange2" ><a href="<?php echo base_url();?>v/<?php echo $this->uri->segment(3);?>/<?php echo $v['uniq'];?>"><?php echo trim(strip_tags($v['video_name']));?> ...

What is the method for locating a particular link within a concealed row of a table solely based on linkText/linkName, without resorting to css-selectors or xpath?

Looking for a unique link in a dynamic table Each row in the table expands to reveal more information when clicked. However, since the rows and IDs are constantly changing, finding a specific link by its text is challenging without using xpath. Attempts ...

Unleashing the power of AngularJS to create dynamic interactions between

Is there anyone who can assist me in getting my Country/State drop down dependency example to work? The reason I structured the JSON in this manner is because I want the dependency to be versatile, allowing me to apply it to any drop down using only Meta ...

Tips for querying a MongoDB collection based on a date field?

My date string is formatted like this: '2021-03-09' This is how my mongodb collection looks: { "_id": { "$oid": "633aede250625c10dddfd57b" }, "title": "test 1", "desc ...

Enhance the appearance of the <td> <span> element by incorporating a transition effect when modifying the text

I need help with creating a transition effect for a span element within a table cell. Currently, when a user clicks on the text, it changes from truncated to full size abruptly. I want to achieve a smooth growing/scaling effect instead. You can view an exa ...

Breaking down an array into groups - where did I go wrong in my code?

Check out the following code : function splitArrayIntoGroups(arr, size) { // Splitting the array into groups. var newArray = []; for(var i = 0; i < arr.length; i++){ for(var j = 0; j < size; j++){ newArray.push(arr.splice(0, size)); ...

A function in Angular 2 that subscribes to an Http Observable callback

I am facing an issue with the .subscribe function in my code. Firstly, I have a function that sends a request to the server. protected sendRequest(data:string,url:string):Observable<any>{ let headers = new Headers({ 'Content-Type': &a ...

Tips for resolving undefined error handling in node.js

const fileSystem = require('fs'); const fileName = './prices.json'; const file = require(fileName); const price = require('./prices.json'); const fileName = './prices.json'; if(tmd = message.match(/^!change max ...

Problems with spacing in Slick slider and lazyYT integration

Utilizing lazyYT helps to enhance the loading speed of YouTube videos. Once loaded, these lazyYT videos are then placed within a slick slider. However, an issue arises where the videos stick together without any margin between them. To address this problem ...

Top method for constructing a JSON object by combining data from two queries and a joining table

Currently, I am developing a small webservice in Node.js to handle commands in a restaurant using Express.js. In my database, I have the following tables: DISH(id,name) COMMAND(id,table,status) COMMAND_DISH(idCommand,idDish,quantity) I am interested in ...

Encountering an error due to an unidentified provider for a resolved value

I am currently working on a basic Router setup: .when('/login/:id', { templateUrl: 'views/login.html', controller: 'RoomLoginCtrl', resolve: { roomData: function($route, S ...

Removing a field in a Mongoose document using findByIdAndUpdate()

My method involves sending documents using expressjs to my server, updating the document with request body JSON data (partial document), and passing it to findByIdAndUpdate() function. Previously, using null as a field value would remove the field success ...

Express.js: The global error handler middleware is unable to handle a throw within middleware functions

I have been attempting to utilize middleware as a router in my code. Here is what I have so far: // index.js const router = require('./routers/router'); app.use('/api/a', router) // router.js const router = require('./routers/rout ...

Definition of JointJS type

Being a beginner in typescript, I am attempting to utilize the jointjs definition file with typescript 2.2. You can find the definition file on GitHub at: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/jointjs/index.d.ts To import j ...

Set a variable in PHP by passing a value

In continuation of my previous post, I realized I missed a point and needed to start a new thread. Thankfully, I found a solution for the issue in my previous post and here is the final code: Scrapping code not working in php <?php $html = file_get_co ...

The Ajax function effortlessly receives the returned value and smoothly transitions to the error handling stage

When trying to retrieve data from an ajax request, my function needs to receive the returned data as an array of strings. During debugging, I am able to see the response, but at the same time, the error function is triggered. This is how my code looks: ...

Is there a way to include a URL as a parameter in the router.get() function?

I am facing an issue with passing a URL http://localhost:3000/new/https://www.example.com as a parameter to router.get('/new/:url', function..). Instead of receiving the desired url (https://www.example.com) in req.params.url, I am encountering a ...

Submit a data array using formData through axios

I am planning to send array data using formData. The backend is set up to accept the data array separated by a dash ; For example, if I were to use Postman and input the form-data like this: id_barang : 122;288;383 (sending 3 values of id with dashes ;) W ...

Why are the HTML links generated by JS not opening in Chrome?

<a href='http://www.xyz.hu/xyz' alt='Kosár' title='Kosár'>Megtekintés</a> Additionally: - A setInterval function refreshes the sibling's content every second, although it should not affect this specific el ...

Exploring Firebase's Collection Retrieval through Vue.js

Trying to retrieve a specific collection from Firebase Firestore is giving me an error that I haven't been able to resolve yet. Below is the code snippet from my boot file: import { initializeApp } from "firebase/app"; import { getFirestore ...