Angularjs - Foreach, Managing post tags

by Galo Aragoneses

HTML

<link rel="stylesheet" href="http://getbootstrap.com/dist/css/bootstrap.min.css">
<div ng-app>
  <h2>Tags</h2>
  <div ng-controller="controller">
    <input style="width: 100%" type="text" disabled='disabled' data-ng-value='allTags()' />
      <br /> <br /> 
    <div>
        <span data-ng-repeat="tag in tags">
            {{tag}} <input type="button" class="btn btn-primary" data-ng-click="deleteTag($index)" value="X" title="delete tag" />
        </span>
    </div>
      <br /> <br /> 
    <input type="text" data-ng-model="tagText"  size="30"
             placeholder="add new todo here">
    <input class="btn bbtn-primary" type="button" value="add" 
                 data-ng-click="addTag()"
                 data-ng-disabled="tagText == ''">
  </div>
</div>

JavaScript

function controller($scope) {
  $scope.tags = [
  ];

  $scope.addTag = function() {
    $scope.tags.push($scope.tagWithoutSpaces());
    $scope.tagText = '';
  };
    
  $scope.tagWithoutSpaces = function () {
      var _tagWithout = $scope.tagText.replace(/\s+/g, " "),
          _tagWordsArray = _tagWithout.replace('-',' ').split(' '),
          _tag = _tagWordsArray[0];
      
      angular.forEach(_tagWordsArray, function (tagWord, index) {
          if (index > 0)
              _tag += '-' + tagWord;
      });
      
      return _tag;
  };
    
  $scope.allTags = function () {
    return $scope.tags.join();
  };

  $scope.deleteTag = function(index) {
      $scope.tags.splice(index, 1);
  };
}