如何制作一个ng重复过滤器,为每个对象插入相应的html和{{expression}}

How can I make an ng-repeat filter that inserts the corresponding html and {{expression}} for each object?

本文关键字:插入 对象 expression html 何制作 一个 ng 过滤器      更新时间:2023-09-26

基本上,

我有一个数组。

阵列中每个对象的某些属性不同。

当ng repeat遍历数组时,它应该通过一个过滤器来决定使用什么html代码,以显示每个具有自己div类的对象的首选属性。

(function() {
var app = angular.module('Veggies',[]);
app.controller('ArrayController', function(){ 
    this.Array = Array;
});   
var Vegetebles = [
    {Veg_name: 'Onion', price:2.95},
    {Veg_Article_Title: 'Garlic in Italy', year:20-10-2011},
    {Veg_name: 'Carrot', price:3.95},
    {Veg_name:'Celery', price:2.95},
    {Veg_Article_Title:'Lettuce Growing 101', year:20-10-2011},
    {Veg_name:'Pepper', price:3.95}
];
})();

我需要实现以下目标:

如果对象的某个位置有一个"Veg_Article_Title"键,那么它就是一篇文章,应该将相应的html代码与自己的div类一起使用,这样它的样式就可以与键为"Veg_name"并且是蔬菜的对象不同。

我试过这样做:

$scope.filter = function(Array){
    angular.forEach(Array,function(value, key){
        if (key === Veg_Article_Title){
        $scope.myHTML = 
        "<div class = "Article_Title"><h1>{{Object.Veg_Article_Title}}</h1></div>"
        "<div class = "Article_Year"><h2>{{Object.year}}</h2></div>";  
        }else (key === Veg_name){
        $scope.myHTML = 
        "<div class = "Vegeteble"><h1>{{Object.Veg_name}}</h1></div>"
        "<div class = "Vegeteble_Price"><h2>{{Object.price}}</h2></div>";         
    };
    }

我真的不确定我是否正确地处理了这个问题,也找不到类似的东西。

我对编码还比较陌生,所以请原谅任何语法错误。

非常感谢!

请使用ng repeat指令迭代数组。

HTML代码:

<div ng-repeat="d in Vegetebles">
    <div ng-if="d.Veg_name">Veg Name :  {{d.Veg_name}}</div> <!--Put your html if veg name found-->
    <div ng-if="d.Veg_Article_Title">Article Name : {{d.Veg_Article_Title}}</div> <!--Put your html if veg article title found-->
</div>

JS控制器内部代码:

$scope.Vegetebles = [
            { Veg_name: 'Onion', price: 2.95 },
            { Veg_Article_Title: 'Garlic in Italy', year: 20 - 10 - 2011 },
            { Veg_name: 'Carrot', price: 3.95 },
            { Veg_name: 'Celery', price: 2.95 },
            { Veg_Article_Title: 'Lettuce Growing 101', year: 20 - 10 - 2011 },
            { Veg_name: 'Pepper', price: 3.95 }
        ];