Andurit Andurit - 4 months ago 13
AngularJS Question

Angular - Controller refresh after using ng-click

i have a controller which is basicly one object, and inside of object i have functions.

At start i set default values for variabiles and use

init()
function to get data from database.

Whole page works correctly exept one thing. Somehow I get in trouble when I use my ng-click to remove from choosen

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


My whole controller initialize again, so set all values to default and call
init()
function. I can't figure out why is this happening.

"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;
}]);


Any idea what I am doing wrong?

Answer

When using an anchor tag to perform a click function, even if it's not linked to anything, it will refresh the page by default. In order to prevent this, pass the event object to the function you are calling and use prevent default like so:

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