Search code examples
angularjsinputangularjs-ng-repeatangular-ngmodel

Adding and removing elements to/from the list (AngularJS)


I have two list:

  1. list with alredy exist cities
  2. list from which I can add new cities to my first list.

If I type name it's OK, it is creating new item in first list. What I want to rich is adding cities to the first list by click on the elements from the second list (first check one city and then confirm action by pressing button). A tried to get name of the clicked element via jQuery and put it into input, so to be able in the next step to confirm adding.

$(document).on('click', '.city', function () {
    var input = $('.city-input'),
        inputValue = input.val();
    input.val($(this).text());
    return false;
});

And it takes the name, and it puts this name into the input. But when I'm pressing button - it creates only empty element...

If I've typed something, then press button - it creates an element. Then if I press any city from second list - it appears in the input field, but after I press confirmation button it creates element with previous typed text...

Also, I've tried to create directive, but this still doesn't work..

addCityApp.directive('searchList', function() {
    return {
        scope: {
            searchModel: '=model'
        },
        link: function(scope, element, attrs) {
            element.on('click', attrs.searchList, function(){
                scope.searchModel = $(this).text();
                scope.$apply();
            });
        }
    };
});

Here is my DEMO


Solution

  • I have modified your code using pure angular, here is the code: http://jsfiddle.net/yxtwhos6/25/

    $scope.setCity = function(city) { $scope.newItemName = city;};
    

    I tried to change your code as least as I can.