简体   繁体   中英

inject HTML when enter key pressed on input

I have an input field and when people press enter I'd like the field to be emptied and its value printed below with an 'x' icon to delete it afterwards just like the 'search' field on angel.co: https://angel.co/jobs

Here is my HTML:

      <form ng-submit="searchAds(searchInput)">
        <input id="search-field"  type="search" placeholder="Start typing your search..." ng-change="searchRequest()" ng-model="searchInput"/>
      </form>
      <div id="search-tags"></div>

And my JS in my controller:

$scope.searchAds = function(item){
    if (item === "") return;

    $scope.searchInput = "";
    $('#search-tags').append('<div ng-show="showDetails">' + item + '<div ng-click="showDetails = ! showDetails"> (my DVG icon here) </div></div>');
}

I have 2 problems here:

1 - I believe the code is not compiled when printed so the 'ng-show' and 'ng-click' are so working - how can I make this work?

2 - How can I make sure that when there are several tags, when clicking on my delete icon it hide only this specific tag?

Many thanks

Why not angular instead of jQuery?

You can add a directive to manage the "enter" key:

angular.module('yourModule').directive(
    'ngEnter', 
    function () {
        'use strict';

        return function (scope, element, attrs) {
            element.bind("keydown keypress", function (event) {
                if(event.which === 13) {
                    scope.$apply(function (){
                        scope.$eval(attrs.ngEnter);
                    });

                    event.preventDefault();
                }
            });
        };
    });

And then change a bit your code:

<form ng-submit="searchAds(searchInput)">
  <input type="search" placeholder="Start typing your search..." ng-enter="add(searchInput)" ng-model="searchInput"/>
</form>
<div ng-repeat="tag in tags">
    <div>{{tag}}<div ng-click="delete(tag)">(my DVG icon here)</div></div>
</div>

Your controller:

$scope.add = function(item) {
  $scope.tags.push(item);
  $scope.searchInput = "";
}

$scope.delete = function(item) {
  var index = $scope.tags.indexOf(item);

  $scope.tags.splice(index, 1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM