简体   繁体   中英

How can I create a filter that formats an HTML tag around each element in a generated array?

I have an array that holds the values that the user inputs. The number of inputs and therefore the number of elements is based on a button click like so:

<input type="text" id="genTxt" placeholder="Enter an item" ng-model="genExpr.genArrays[$index]" ng-repeat="genArray in genExpr.genArrays track by $index">
<button ng-click="addTxtField()">Add item</button>
<button ng-click="removeTxtField()">Remove item</button>

With the related Javascript:

var app = angular.module("outputApp", []);

app.controller("outputCtrl", function($scope) {

$scope.genExpr = { genArrays: [] };

$scope.addTxtField = function() {
$scope.genExpr.genArrays.push('');
}

$scope.removeTxtField = function() {
$scope.genExpr.genArrays.pop('');
} 

});

What I need is a filter that is able to wrap each element in genArrays with an html tag, such as <li></li>. So far the closest I've gotten is the following.

app.filter('liTag', function () {
return function (items) {
            return "<li>" + items + "</li>"
};
});

Which creates the tags even if the array is empty and around the entire array as well.

<ul><li>test,test,test,test</li></ul>

The goal, rather, would be this.

<ul><li>test</li><li>test</li><li>test</li><li>test</li></ul>

My other attempts have failed, including one where the filter had a conditional and returned "" if the array is empty.

I have the whole of it in plunker for easier viewing.

https://plnkr.co/edit/8FVrcOwOgr1wze4By4Hz?p=preview

You need to simply loop through the individual elements in the array and add the li tags like so.

 var app = angular.module("outputApp", []); app.controller("outputCtrl", function($scope) { $scope.genExpr = { genArrays: [] }; $scope.addTxtField = function() { $scope.genExpr.genArrays.push(''); } $scope.removeTxtField = function() { $scope.genExpr.genArrays.pop(''); } }); app.filter('liTag', function() { return function(items) { var result = "" for (var item of items) { result += "<li>" + item + "</li>"; } return result }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="outputApp" ng-controller="outputCtrl"> <input type="text" id="genTxt" placeholder="Enter an item" ng-model="genExpr.genArrays[$index]" ng-repeat="genArray in genExpr.genArrays track by $index"> <button ng-click="addTxtField()">Add item</button><button ng-click="removeTxtField()">Remove item</button> <textarea id="output">&lt;ul>{{ genExpr.genArrays | liTag }}&lt;/ul></textarea> </div> 

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