Mahesh K
Mahesh K

Reputation: 1697

Dynamic string split while binding data in angularJS

I am trying to implement chips style. Adding tags and remove tags like chips style to an item, for that I need to split string and bind separately based on length of array of split.

How to split comma speared dynamic length string while binding data.

how can I use angular filters here
Please check following code.

JS: Controller:

var app = angular.module('myApp',[]);
app.controller('myCtrl', function($scope) { 
  var temp= {
  "values": [
    {
      "id": "1",
      "tags": "Design research, UI Frameworks, Wireframes" 
    },
    {
      "id": "2",
      "tags": "Hockey, basketball, Cricket, Football, Baseball"
    },
    {
      "id": "3",
      "tags": "Sensors, maps, Location Service, Studio"      
    },
  ],
  "count": "3"
};
 // I have json like this
 $scope.items = temp.values; 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" >
<div ng-controller ="myCtrl">
  <p ng-repeat="item in items">
  <span>{{item.tags}}</span>
  </p>
  </div>
  <hr>
  <!-- here  I am trying implement chips style -->
  <!-- Requieremrnt-->
  <span style="background:#ddd;">{{item.tags[0]}}</span>
   <span style="background:#ddd;">{{item.tags[1]}}</span>
  <span style="background:#ddd;">{{item.tags[n]}}</span>
  <!-- can I use ng-repeat or custom filter. if yes how??--> 
  <hr>
  </body>

Can I use ng-repeat or custom filter. if yes how??

Thanks.

Upvotes: 2

Views: 1819

Answers (1)

dmlittle
dmlittle

Reputation: 999

There is no need to create a custom filter to do so (although you can if you want to).

For this particular purpose, you can split the tags in your controller and then simply iterate through the strings in your view. In this case we'll use a double ng-repeat. The first one to iterate through all group of strings in each set of tags and the second one to iterate through the split string items. I've modified your code below and cleaned it up a bit.

var app = angular.module('myApp',[]);
app.controller('myCtrl', function($scope) {

  var temp= {
  "values": [
    {
      "id": "1",
      "tags": "Design research, UI Frameworks, Wireframes" 
    },
    {
      "id": "2",
      "tags": "Hockey, basketball, Cricket, Football, Baseball"
    },
    {
      "id": "3",
      "tags": "Sensors, maps, Location Service, Studio"      
    },
  ],
  "count": "3"
};
                       
 $scope.items = temp.values.map(function (item) {
  return item.tags.split(",");
 });
      
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp" >
  <div ng-controller ="myCtrl">
    <div ng-repeat="group in items">
      <p ng-repeat="tag in group">{{tag}}</p>
      <hr />
    </div>
  </div>
</body>

Upvotes: 1

Related Questions