Refresh Angular controller after ng-click event is triggered

In my current setup, I have a controller that consists of one main object containing various functions.

Initially, default values for variables are set and the init() function is used to fetch data from the database.

Everything on the page seems to be functioning correctly except for one issue. Whenever I trigger the ng-click event to remove an item from the chosen list,

  <a href="#" ng-click="listCtrl.removeFromChosen(chosen)" class="tagselect__close">
     <span class="glyphicon glyphicon-remove remove-icon" aria-hidden="true"></span>
  </a>

The entire controller gets re-initialized, resetting all values to default and calling the init() function again. It's puzzling why this behavior occurs.

"use strict";
myApp.controller('ListCtrl', ['$scope', '$cookies', '$http', function ($scope, $cookies, $http) {

    var listCtrl = {
        candidate: {},
        candidates: [],
        positions: [],
        chosenPositions: [],

        init: function () {
            listCtrl.getCandidates();
            listCtrl.getPositions();
        },
        getCandidates: function () {
            $http.get('api/v1/candidates/getCandidates.php').then(function (res) {
                listCtrl.candidates = res.data;
            });
        },
        getPositions: function () {
            $http.get('api/v1/positions/getPositions.php').then(function (res) {
                listCtrl.positions = res.data;
            });
        },
        removeFromChosen: function (position) {
            var index = listCtrl.getChosenIndex(position);
            listCtrl.chosenPositions.splice(index, 1);
            //console.log(listCtrl.chosenPositions);
        },
    };

    listCtrl.init();
    $scope.listCtrl = listCtrl;
}]);

Does anyone have any insights into what might be causing this unexpected behavior?

Answer №1

If you are using an anchor tag to trigger a click function, even without a link, the default behavior will be to refresh the page. To prevent this from happening, make sure to pass the event object to the function being called and include `event.preventDefault()` in your code like shown below:

removeFromChosen: function (event, position) {
        event.preventDefault();
        var index = listCtrl.getChosenIndex(position);
        listCtrl.chosenPositions.splice(index, 1);
        //console.log(listCtrl.chosenPositions);
    }

Answer №2

Eliminate the href="#" attribute as it is not suitable for use with ng-click.

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

Devices such as CAC cards and smart cards are not being recognized by Chrome's WebUSB feature

I recently developed a script to identify all USB devices connected to Chrome using chrome.usb.getDevices. Surprisingly, the script successfully detected a second-generation iPod touch, a mouse, keyboard, and two unidentified items from Intel. However, it ...

What is the best way to store React form data in a queue for future processing?

I am currently developing a ticketing system in React, utilizing Node.js for the backend and Python for the email server. My goal is to process form submissions by extracting all the form data, creating an instance of a plain JavaScript class with only a ...

Routes are not functioning properly on Ionic Angular

Currently, I am facing a challenge while working on an Ionic App. As a newcomer to AngularJS and Ionic, I find myself struggling. In order for users to access the app, they must be logged in. A call to my server is made upon entering the app to verify thi ...

What is the process for encrypting and decrypting image files over the internet?

I'm currently developing a web application that requires loading images into a canvas object, followed by extensive manipulation. My goal is to conceal the original source image file (a jpeg) in such a way that users on the client side cannot access i ...

EJS not displaying object values properly

I'm currently in the process of setting up a blog and I want to create a page that displays the titles of all the articles I've written. For example: List of Articles: * Title: Article 1 * Title: Article 2 * Title: Article 3 Below is my Schem ...

The class "pagination pagination-lg" from the link https://angular-ui.github.io/bootstrap/#/pagination seems to be malfunctioning in Bootstrap 4

Just starting out with angularjs and I'm trying to implement pagination using https://angular-ui.github.io/bootstrap/#/pagination. However, I'm facing an issue where the style class "pagination pagination-lg" is not applying properly. I'm cu ...

Mastering the usage of AngularJS Directive controllerAs syntax with scope is key to developing

I have included my code below: // HTML <body> <h1>{{foo.name}}</h1> <my-directive></my-directive> </body> // Scripts app.directive('myDirective', function() { return { restrict: 'E', ...

Creating a clone of JSON for use as a template

I am working with a json template that I fill with product data. Here is an example of the json structure: // product template $scope.productAttributes = { "Code": null, 'Attributes': {} }; When a user inputs produ ...

Adding DOM elements dynamically from a controller in Angular.js is a powerful feature that

Hey there, I'm just getting started with Angular and may not be using the best practices yet. One thing I'm working on is appending a <circle> element within the controller function called placeShot(), which is triggered by ng-click='p ...

issue with useReducer not functioning as expected

I encountered an issue with my customized Select component. It includes a select and options while listening for onChange events. Additionally, I am using a useReducer function that initializes some variables. However, even after selecting an option, the s ...

Animating Jquery to smoothly change opacity until it reaches 100% visibility

The script I have does several things, but the main issue lies in the last line where the opacity of the class doesn't seem to reach 100%.... $('.fa-briefcase').parent().on('click', function () { $("#colorscreen").remove(); ...

Embed three.js within a div container in an HTML document

I've been attempting to place the Canvas Lines three.js inside another div, but it doesn't seem to be working as expected. Instead, when I try, the JS code places the canvas at the very end of the body. Can anyone tell me why this is happening? ...

Extending State Interface in ReactJs and Typescript: A Step-by-Step Guide

I have the following: interface EditViewState<T> { entity?: T; } abstract class EditView<T, P, S> extends React.Component<P, EditViewState<T> & S> { constructor(props: P, ctx: any) { super(props, ctx); this. ...

I am looking to pass several parameters through the post method by utilizing ajax

Can someone assist me with this code? I am trying to pass the item ID, stock quantity, and price using AJAX in a POST method. Any help would be greatly appreciated. Thank you in advance! function updateItemDetails(itemId, sellingPrice, stockQty){ v ...

What is the best way to connect an external JSON file to an Angular controller?

As I embark on my first Angular JS project, I find myself in need of exporting a JSON array from my controller to an external JSON file. Here is the snippet from my controller containing the JSON data: Fantacalcio.controller('fantacalcioController&ap ...

Utilizing database information to dynamically select Nightwatch.js tests for execution

Currently, I am in the process of configuring nightwatch tests for a specific website. The setup involves assigning testing personas to run tests, which works smoothly in our development environment. However, we face an issue when we need to dynamically ad ...

Exploring the Power of Vue 3 in Manipulating the DOM

Hello everyone, I am a beginner with Vue and I am interested in learning how to modify the DOM without relying on methods such as document.querySelector or getElementById. Let's take for instance this input: <input id="myInputId" class=& ...

javascript create smooth transitions when navigating between different pages

As a newcomer to JS, I am currently working on creating a website with an introduction animation. My goal is to have this animation displayed on a separate page and once it reaches the end, automatically redirect to the next webpage. <body onload="setT ...

Error encountered in Express Router middleware (`app.use() function must be provided with a middleware function`)

I've seen plenty of similar questions on this topic, but after reviewing them all, I still haven't found a solution. My current dilemma involves creating an app using Express Router, however I keep encountering the following error: app.use() re ...

The console is showing the Ajax Get request being logged, but for some reason it is not displaying on the

Could someone please explain why this response isn't displaying on the page? $.ajaxPrefilter( function (options) { if (options.crossDomain && jQuery.support.cors) { var http = (window.location.protocol === 'http:' ? &apos ...