1

I have a controller which is basically one object, and inside of that object I have functions.

At the start I set the default values for variables and use init() function to get data from database.

The whole page works correctly except for one thing. Somehow I get in trouble when I use my ng-click to remove from chosen

  <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 is initialized again, so it sets all the values to default and calls init() function again. 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?

2 Answers 2

2

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);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Hi @Cameron637, thanks for nice explenation. you are right :)
2

Remove href="#" which is not compatible with ng-click.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.