Creating a unique field button in AngularJS that is dynamically generated and specifically targeted as the last button

Is there a way to enable the plusSign = true option only for the last item in the dynamic input field?

(function() {
  var app = angular.module('managementApp', []);
  // var app = angular.module('managementApp', ['ngRoute']);
  app.controller('phonebookController', function($scope, $http) {
    $scope.dynamicField = function(buttonStatus, inputIndex) {
      if (!buttonStatus) {
        $scope.currentContact.contacts.push({
          "phone": ""
        });
      } else {
        $scope.currentContact.contacts.splice(inputIndex, 1);
      }
    };
    $scope.currentContact = [{
      "phone": "07875 506 426"
    }, {
      "phone": "+91 9895 319991"
    }, {
      "phone": "+44 7875 506 426"
    }];

    $scope.checkIndex = function(totalCount, indexCount) {
      indexCount++;
      /*if (totalCount === indexCount) {
//alert("last one");
$scope.plusSign = true;
}else{
$scope.plusSign = false;
}*/
    };
  });
})();
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="managementApp">
  <div class="row" ng-controller="phonebookController">
    <div class="form-group" ng-repeat="contact in currentContact" ng-init="checkIndex(currentContact.length, $index);">
      <label for="contact-number3" class="col-sm-3 control-label">Contact number {{$index + 1 }}</label>
      <div class="col-sm-9">
        <div class="input-group">
          <input type="tel" class="form-control" placeholder="Contact number {{$index + 1 }}" ng-model="contact.phone">
          <span class="input-group-btn">
            <button class="btn btn-default" type="button"  ng-init="plusSign = true" 
              ng-click="plusSign = !plusSign; dynamicField(plusSign, $index);">
              <i class="glyphicon " ng-class="plusSign ? 'glyphicon-plus' : 'glyphicon-minus'"></i>
            </button>
          </span>
        </div>
      </div>
    </div>
  </div>

</div>

Answer №1

Utilize $last within ng-repeat to determine if the element being repeated is the last one in the iteration. Alternatively, you can achieve this using CSS alone with .row:last-of-type {/**/}.

Answer №2

Look at the $last variable in your function as shown below:

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="managementApp">
  <div class="row" ng-controller="phonebookController">
    <div class="form-group" ng-repeat="contact in currentContact" ng-init="checkIndex($last);">
      <label for="contact-number3" class="col-sm-3 control-label">Contact number {{$index + 1 }}</label>
      <div class="col-sm-9">
        <div class="input-group">
          <input type="tel" class="form-control" placeholder="Contact number {{$index + 1 }}" ng-model="contact.phone">
          <span class="input-group-btn">
            <button class="btn btn-default" type="button"  ng-init="plusSign = true" 
              ng-click="plusSign = !plusSign; dynamicField(plusSign, $index);">
              <i class="glyphicon " ng-class="plusSign ? 'glyphicon-plus' : 'glyphicon-minus'"></i>
            </button>
          </span>
        </div>
      </div>
    </div>
  </div>
</div>

This is the controller method:

$scope.checkIndex = function(last) {
       if (last === true) {
                    $scope.plusSign = true;
                } else {
                    $scope.plusSign = false;
                }

    };

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

What is the best way to prevent a folder from being included in the next js build process while still allowing

I am faced with a challenge involving a collection of JSON files in a folder. I need to prevent this folder from being included in the build process as it would inflate the size of the build. However, I still require access to the data stored in these file ...

Increase the detection range in empty lists for Vue-draggable-next

I am currently utilizing Vue-draggable-next in conjunction with Vue 3 to enable draggable lists within my application. In certain scenarios, users need to drag items from other lists into lists that are initially empty. I have noticed that the area for det ...

Unable to access account due to login function malfunctioning

I've created a login button with this function code, but I keep getting the error message "Login unsuccessful, Please try again..." Thank you in advance. I wasn't entirely sure what you needed, so I included most of the code because I've b ...

Add a new sibling item to Angular-UI-tree

I am trying to add a sibling item to a tree when clicked in angular-ui-tree (https://github.com/angular-ui-tree/angular-ui-tree) Here is an example of what I currently have: <item><input value"item A #1"><button>insert under</button& ...

Troubleshooting the issue with reactdom.render() functionality in CodeSandbox

Having issues with ReactDom in CodeSandbox for React. The HTML file includes: <body> <div id="root"></div> </body> <script src="scr/index.js"> The JavaScript file (named index) includes: ReactDOM.rende ...

Unable to save captured signature image during saveEvent function in React Native

I am a beginner in the world of React Native and I am facing an issue with saving a signature image. It seems like the function responsible for this task is not being called properly. I suspect there might be an issue with the onPress event handler, as whe ...

Minifying HTML, CSS, and JS files

Are there any tools or suites that can minify HTML, JavaScript, and CSS all at once? Ideally, these tools should be able to: Identify links from the HTML document and minify the associated JavaScript and CSS. Remove any unused JavaScript functions and CS ...

My code seems to be malfunctioning

I'm attempting to conceal the chatname div. Once hidden, I want to position the chatid at the bottom, which is why the value 64px is utilized. However, I encountered an error stating The function toggle3(); has not been defined. <div id="chat ...

What is the best way to showcase images using Vue.js?

For my Vue project, I am encountering issues with the image paths not working properly. Despite trying different variations, such as: <figure class="workout-image"> <img :src= "images.bicep" width= "200px" ...

Mongoose, Angular, and Express are not functioning properly when using the PUT method

I'm having trouble with implementing a basic edit function in my application. The delete and get functions are working fine, but I keep encountering a 500 error when trying to make a put request. I've attempted using findByIdAndUpdate and FindOne ...

Facing a problem with querying interfaces and types in TypeScript

My goal is to pass a variable to an RTK Query API service that uses a typescript interface: const device_id: unique symbol = Symbol(props.id); const { data: device, isFetching, isLoading, } = useGetAssetsByIdQuery(device_id, { pollingInterv ...

AngularJS - Greetings global

Currently experimenting with AngularJS, however I noticed that the official tutorial provides download code and predefined npm dependencies without explaining how to create it from scratch. I am using Linux (Mint Mate 17) with Node.js / npm / bower instal ...

When using the Google Maps API fetch() method, the response is empty. However, when accessing the same

I am currently working on extracting the "photo_reference" from the JSON data provided below; { "html_attributions" : [], "results" : [ { "formatted_address" : "Bandar Seri Begawan, Brunei", "geometry" : { "locati ...

Navigation through Image Filters

Everything seems fine with my code, but when I click on the navigation links, they direct me to index.html or the landing project instead of filtering the images. How can I modify the links to properly filter the images? This is the Javascript and html co ...

Tips for ensuring that divs resize to match the container while preserving their original proportions:

#container { height: 500px; width: 500px; background-color: blue; } #container>div { background-color: rgb(36, 209, 13); height: 100px; } #one { width: 1000px; } #two { width: 800px; } <div id="container"> <div id="one">&l ...

Directive Template with Dynamic Fields (AngularJS)

I am interested in creating a custom directive that can bind to any object, allowing me to specify the field used in the template for display. Previously, I was limited to using {{item.Name}}, but now I want the flexibility to define the display field. Cu ...

Razzle fails to initiate the server

After creating my React project with Razzle.js and downloading it from a repository, I encountered an issue when trying to run it. Upon running yarn start, the screen gets stuck at a message saying the source is compiled and server is running on localhost: ...

Navigate to a new tab using this.router.navigate

Is there a way to redirect the user to a specific page with ${id} opening in a new tab, after clicking a button in an angular material dialog box? I want to leave the dialog box open while querying the new page. Currently, the redirect happens but not in a ...

Sending a JSON object with scheduled task cron job

I have a PHP cron job that is quite complex. It retrieves data from an external webpage and consolidates all the information into one variable, encoding it in JSON. Unfortunately, this entire process is slow and consumes a significant amount of time. My d ...

Showing child elements within a div using AngularJS

I am eager to create a straightforward AngularJS website that will showcase an initially hidden HTML element along with all of its children. Below is the HTML structure snippet I plan to use: <div class="hiddenStuff"> <h3>Game Over</h3&g ...