Deepanjan Deepanjan - 5 months ago 14
AngularJS Question

tagging directive issue how to bind the tags as array of json objects and the tagging shoud work with ng-keypress event

https://plnkr.co/edit/KF9FFdx0sWJkpQ7VKrl2?p=preview
Here is the plnkr. Can anyone help me?
I have my tags list i am not able to bind it with ng-model and want to bind the tags as array of objects on a function call using ng-keypress. and it should post to a json file in this format.
I want something like this:
Eg.

$scope.tags={tag:[
{name:"angular"},
{name:"ruby"},
{name:"pearl"}
]}

Answer

You have to edit your directive to accept json objects not just strings

<script>
  App.directive('dhTag', function($compile) {
    return {

      restrict: 'AE',
      scope: {
        taglist: '=list',
        autocomplete: '=autocomplete',
        display: '='
      },
      link: function($scope, element, attrs) {

        $scope.defaultWidth = 490;
        $scope.tagText = "";
        $scope.placeholder = attrs.placeholder;
        $scope.display = attrs.display;



        $scope.tagArray = function() {
          return $scope.taglist || [];
        };


        $scope.addTag = function() {
          //debugger
          var tagArray;
          if ($scope.tagText.length === 0) {
            return;
          }
          tagArray = $scope.tagArray();

          for (var i = 0; i < tagArray.length; i++) {
            if (tagArray[i].name == $scope.tagText) {
              alert("Tag already exists in the content box!!");
              return;
            }
          }

          tagArray.push({
            name: $scope.tagText
          });
          $scope.taglist = tagArray;
          $scope.tagText = "";
        };


    $scope.deleteTag = function(key) {
      var tagArray;
      tagArray = $scope.tagArray();
      if (tagArray.length > 0 && $scope.tagText.length === 0 && key === undefined) {
        tagArray.pop();
      } else {
        if (key !== undefined) {
          tagArray.splice(key, 1);
        }
      }
      $scope.taglist = tagArray;
    };



    $scope.$watch('tagText', function(newVal, oldVal) {
      var temp;
      if (!(newVal === oldVal && newVal === undefined) && temp) {
        //temp = $("<span>" + newVal + "</span>").appendTo("body");
        $scope.inputWidth = temp ? temp.width() : 0;
        if ($scope.inputWidth < $scope.defaultWidth) {
          $scope.inputWidth = $scope.defaultWidth;
        }
        return temp.remove();
      }
    });

    $scope.processKey = function(e) {
      var key;
      key = e.which;
      if (key === 9 || key === 13 || key === 188) {
        $("div").find('.dh-tag-ctn .input-tag').css({
          "background-color": " #FCF8E3"
        });
        e.preventDefault();
        return $scope.addTag();
      }
      if (key === 8) {
        $("div").find('.dh-tag-ctn .input-tag').css({
          "background-color": "rgba(255, 0, 0, 0.15)"
        });
        $scope.deleteTag();
      }
    };
  },
  //templateUrl: "tagInputTemplate.html",
  template: "" +
    "<div  class='dh-tag-ctn'>" +
    "   <div class='input-tag' ng-hide={{display}} data-ng-repeat=\"tag in tagArray() track by $index\" ng-class='tag' >" +
    "       <span>{{tag.name}}</span>" +
    "       <div class='delete-tag' data-ng-click='deleteTag($index)'>&nbsp;&times;</div>" +
    "   </div>" +
    "   <input type='text' data-ng-style='{width: inputWidth}' ng-model='tagText' ng-keypress='processKey($event)' ng-keyup='processKey($event)' placeholder='{{placeholder}}' />" +
    "</div>" +
    "<br>" +
    "<div ng-show={{display}} class='dh-tag-ctn-view'><div class='input-tag' data-ng-repeat=\"tag in tagArray() track by $index\" ng-class='tag'>{{tag.name}}" +
    "   <div class='delete-tag' data-ng-click='deleteTag($index)'>&times;<br></div>" +
    "</div>"
    };
  });
</script>

You can view your tag value

<div ng-controller='FormCtrl'>
  <h4>tagging directive using angularjs</h4>
  <dh-tag autocomplete='users' list="tag" placeholder='add a tag' display="false"></dh-tag>
  {{ tag }}
</div>

Plunker https://plnkr.co/edit/hCgdCN?p=preview

Just create a button to send data

<input type="button" value="Send" ng-click="UploadToServer()" />

Where UploadToServer() is a function in your FormCtrl

App.controller('FormCtrl', function($scope, $http) {
  $scope.myfunc = function() {
    $scope.tag = {};
    $http({
      method: 'POST',
      url: 'tag.json',
      data: $scope.tag
    }).then(function(response) {});
    return $scope.users = {
      "name": "AngularJS",
      "name": "Javascript",
      "name": "Java",
      "name": "Spring",
      "name": "PHP",
      "name": "Ruby"
    };
  }
  $scope.UploadToServer = function () {
     //insert all logic to send $scope.tag to database
  };
});