AngularJS application: the button requires two clicks to activate

In my attempt to develop a simple CRUD app using AngularJS, I encountered an issue. The initial step involves clicking a button that fetches data from a REST API and populates an array. This array is then iterated using ng-repeat to generate Bootstrap cards with the search results. Oddly enough, I have to click the button twice for the cards to be displayed. Despite the first attempt successfully fetching the data and filling the array, I can't seem to understand why this double-click behavior occurs.

Below is the code in question; any assistance would be greatly appreciated:

var app = angular.module("myModule", []);

app.controller("firstCtrl", function($scope) {

 $scope.showButton = true;
 $scope.arr;
  $scope.$on('myEvent', function(event, data) {
     $scope.arr = data.fromServer.results;
     console.log($scope.arr)
  });

  $scope.back = function(){
   $scope.arr = [];
  }

$scope.delPerson = function(person,$index){
  $scope.arr.forEach( personInArray => {
    if(personInArray.id == person.id){
      $scope.arr.splice($index,1)
      console.log($index)
    }
  });
}

$scope.newNameFirst;
$scope.newNameLast;
$scope.p;

$scope.editPerson = function(person, $index){
  $scope.newNameFirst = ""
  $scope.newNameLast = ""
  $scope.p = person
  console.log($scope.p)
}

$scope.reWriteUser = function(){
  $scope.p.name.first= $scope.newNameFirst;
  $scope.p.name.last= $scope.newNameLast;

}


});

app.controller("secondCtrl", function($scope) {
  $scope.fromServer;   
  $scope.submit = async function() {  
    let one = await fetch('https://randomuser.me/api/?results=9')
    let two = await one.json();   

    $scope.$emit('myEvent', {
      fromServer: two
    });
    
    $scope.showButton = !$scope.showButton;
  }

});
.fa-times-circle:hover{
cursor:pointer;
}

.botones{
    display: flex;
    justify-content: space-between;
}

.rep{
    background: cadetblue;
    border-radius: 12px;
    padding: 10px;
    margin-left: 5px;
    text-align: -webkit-center;
    text-align:center;
    display: inline-grid;
    justify-content: center;
    align-items: center;
}
<!DOCTYPE html>
<html>

<head>
  <title>Anidando componentes</title>
  <link rel="stylesheet" type="text/css" href="./style.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9cfef3f3e8efe8eefdecdca8b2a9b2af">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
</head>
<body>

  <div ng-app="myModule">

    <!--parent div-->

    <div ng-controller="firstCtrl" class="container">    
    <div class="row">
      <div class="col text-center">
          <h3>Anidando componentes</h3>
      </div>
    </div>  
      <div class="row">
        <div class="col rep mt-3" ng-repeat="person in arr">
          <div class="botones">
             <i class="fas fa-times-circle" ng-click="delPerson(person,$index)" ></i>
             <i class="fas fa-edit" ng-click="editPerson(person,$index)" data-toggle="modal" data-target="#exampleModal"></i>
          </div>  
          <div class="card mt-3" style="width: 10rem;" style="display:inline-block">
              <img src="{{person.picture.thumbnail}}" class="card-img-top" alt="person.name.first">
            <div class="card-body">
              <p class="card-text">{{person.name.first}} {{person.name.last}}</p>
            </div>
          </div>
        </div>
      </div>
      
      <!--child div-->
      <div ng-controller="secondCtrl">
        <button type="button" class="btn btn-primary" ng-click="submit()" ng-if="showButton">Show users</button>
        <button type="button" class="btn btn-primary" ng-click="back()" ng-if="!showButton">Back</button>
      </div>

        <!-- Modal -->
  <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true" id="myModal">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <input type="text" name="newName" id="newNameFirst" ng-model="newNameFirst">
          <input type="text" name="newName" id="newNameLast" ng-model="newNameLast">
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary" ng-click="reWriteUser()" data-dismiss="modal">Save changes</button>
        </div>
      </div>
    </div>
  </div>

    </div>
  </div>

<script src="./app.js"></script>

  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80e2efeff4f3f4f2e1f0c0b4aeb5aeb3">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>

</body>

</html>

Answer №1

When it comes to making http requests in Angular.js, the best approach is to utilize the $http service. You can find more information about this in the official documentation

// Here's a simple example of a GET request:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // This callback will be executed asynchronously
    // once the response is received
  }, function errorCallback(response) {
    // This function will handle any errors that occur
    // or if the server returns a response with an error status
});

Angular.js provides support for real-time change detection through its unique 'The Angular way'. It does not track changes made outside of its scope (unlike native JavaScript). While manual detection is possible, it is not recommended for this particular scenario.

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

How can I encode and decode a base64 string using AngularJS1 and TypeScript?

I am currently working with Angular1 using TypeScript and I have a question that needs some clarification. Within the environment that I am operating in, is there a method available to encode and decode a string in base64? Despite conducting extensive re ...

The server tag is displaying an error due to incorrect formatting in the hyperlink data-binding section

I'm currently facing an issue with the formatting of my hyperlink. The text part of the hyperlink is working fine, which leads me to believe that the problem lies within the JavaScript. However, I am unable to pinpoint the exact issue. <asp:Templa ...

Display a specific tab section upon clicking using jQuery or JavaScript

Hello everyone! I am completely new to JavaScript. I have added a tab slider to my HTML with 3 categories in the tab menu: All, Creative, and Branding. How can I show a div after clicking on one of the list items? I have assigned classes to the list items ...

Guide to implementing an ES6 template within an HTML anchor tag href

Hello there, this is my first time seeking assistance here. I have an ajax request returning a JSON response. Now, I am aiming to use the response data to dynamically generate recipe titles and also create clickable links with that data. $( window ).load( ...

What could be causing the second switchMap to be triggered repeatedly upon subscription?

Check out the code snippet below for reproducing the issue: import { defer, BehaviorSubject, of } from "rxjs"; import { shareReplay, switchMap } from "rxjs/operators"; const oneRandomNumber = defer(() => of(Math.floor(Math.random() ...

javascriptHow to specify the character set in a Data URI

In a UTF-8 page, I am implementing the following code: var data = "a\tb\tc\r\nd\te\tf"; window.location.href = "data:text/csv;charset=utf-8," + encodeURIComponent(data); This code is used to prompt the browser to download an ...

Display conceal class following successful ajax response

Upon clicking the button, the following script is executed: $.ajax({ url: "<?php echo CHILD_URL; ?>/takeaway-orders.php", type: 'POST', async:false, data: 'uniq='+encodeURIComponent(uniq)+'&menu_id=' ...

Tips on connecting data within a jQuery element to a table of data

I am currently developing a program that involves searching the source code to list out element names and their corresponding IDs. Instead of displaying this information in alert popups, I would like to present it neatly within a data table. <script> ...

Is ReactJS known for its exceptional performance in rendering large matrices?

Although I have no prior experience with ReactJS, I've heard about a great feature it offers called virtual DOM. It reminds me of the concept of virtual elements in Silverlight where invisible elements are removed from the tree to enhance user-perceiv ...

Struggling to access notification payload from firebase-sw within Ionic PWA

After spending countless hours trying to solve this issue that has been plaguing me for a week, I have hit a roadblock. My Ionic PWA project receives notifications from Firebase without any issues when the app is open, but I am unable to retrieve the paylo ...

A guide on extracting the values of checked checkboxes by their ID using javascript

I'm currently attempting to extract the values of selected checkboxes. These checkboxes have distinct IDs because they are specified within a modal window. <input type = 'checkbox' id = 'audience_Name-$row[asset_ID]' value = &a ...

Initiating a conversation using a greeting in the Javascript bot framework

I am looking to initiate a multi-level, multiple choice dialog from the welcome message in the Bot Framework SDK using JavaScript. I have a main dialog (finalAnswerDialog) that utilizes LUIS for predicting intents, and a multi-level, multiple choice menu d ...

What is the appropriate content-type to use when sending AJAX POST data?

Having an issue sending base64 image data using ajax post. I suspect the problem lies with the Content-Type value, as I have tried using application/json, text/json, and image/jpeg without success. Javascript function sendFormData(fD) { var urls = fD ...

How can I utilize React to pull information from the Google Taxonomy API?

Seeking assistance with React development, as I am a beginner and looking to retrieve data from this URL and organize it into a tree structure. I not only want to fetch the data but also display it in a tree format. My current code successfully retrieves t ...

When I try to move my object, it seems to have a mind of its own and flies off the canvas instead of staying where

I am in the process of developing a simple game for a class project. Currently, I am working on ensuring that my rectangle stays within the boundaries of the canvas as I move it using a bounce function. However, I am facing difficulties as the rectangle ...

Integrate AngularJS service with Angular framework

Attempting to utilize the $log service within an angular 2 app, it seems that the following steps are necessary: Set up a module that includes the service you wish to inject. Utilize UpgradeAdapter's upgradeNg1Provider method. Therefore, I proceede ...

When attempting to display an identical image on two distinct canvas elements in Angular 6

I am facing an issue where the image is only rendered on the second canvas instead of both canvases. I need assistance in finding a solution to render the same image on both canvases. Below is a screenshot demonstrating that the image is currently only re ...

Having trouble embedding Hangouts button in HTML template using script tags

When I include a Hangouts button on my index page, it is visible and functional as expected: <body ng-app="sampleApp" ng-controller="MainCtrl"> <div class="row"> <div class="col-md-12 m-body"> <div class="m ...

The website is experiencing functionality issues with Ajax

On my personal website, I am trying to add a simple ajax server clock in the header section but unfortunately it is not appearing as expected. Here's the snippet of Javascript code that I am using: var httpxml; try { // Firefox, Opera 8.0+, Safari ...

The SyntaxError message indicates that there was an unexpected non-whitespace character found after the JSON data when parsing it

I received an Error message: SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data Here is the code snippet: <script> $(document).ready(function () { $('.edit1').on('change', function () { ...