简体   繁体   中英

How to create a new model property that combines data from model record

In AngularJS 1.2, I have a controller that reads JSON data into single records. Those records (Conference Sessions) each have arrays in them that are the Session Speakers. That is, something like:

data: [{title: 't1',speakers: ['speaker1','speaker2']},...]

I want to write some JavaScript that will combine the speakers so that in my ng-repeater I can output them simply. That is, I want to create a new property in the model that is a comma separated list of speakers.

If I use th ng-repeater, I'm having issues killing the trailing comma and also not having that data in a span or div causing a line break.

If I'm interpreting your question correctly do you want to do something like the following:

module.controller('Controller', ['$scope', function ($scope) {
    var data = [
            {title: 't1', speakers: ['speaker1', 'speaker2']}
        ],
        speakers = [];

    angular.forEach(data, function (object, i) {
        speakers = speakers.concat(object.speakers);
    });

    $scope.allSpeakersText = speakers.join(',');
}]);

If you only want to combine the speakers for the view then a filter would be the right choice. There is no combination filter built in, but it's easy to create:

module.filter('combine', function() {
  return function(array) {
    return array.join(', ');
  }
});

In your view:

<p>{{data.speakers | combine}}</p>

The output would be:

<p>speaker1, speaker2</p>

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