如何在foreach循环中编译HTML字符串

时间:2014-07-30 07:51:37

标签: angularjs google-maps compilation directive

我正在尝试编译位于foreach循环内的HTML String指令。我甚至尝试过放置范围但仍然没有工作。我的示例代码如下所示:

hotelierApp.directive('maps', ['$translate', '$filter', '$compile',
function ($translate, $filter, $compile) {
return {
    restrict: "A",
    replace: true,
    scope: true,
    link: function (scope, element, attrs) {
        _.each(scope.properties, function (property) {                    
                    var strHtml = $compile('<div><div class=\'hotelMarker\'>' +
                        '<div class=\'hotelIcon\'>' +
                        '<img alt=\'\' class=\'menuShadow\' src=\'{{PropertyThumbnail}}\' height=\'45\' width=\'45\'/>' +
                        '</div>' +
                        '<div class=\'hotelText\'>' +
                        '<span class=\'hotelHeader\'>{{PropertyName}}&nbsp;' +                            
                        '</span>' +
                        '</div>' +
                        '</div></div>')(property);
                    return function () {
                        if (infoWindow) {
                            infoWindow.close();
                        }
                        infoWindow.setContent(strHtml[0].innerHTML);
                        infoWindow.open(map, markerOtherHotel, strHtml[0].innerHTML);
                    }
                })(markerOtherHotel, property.PropertyID));
            });                            
    },
    template: ''
}}]);

请帮忙

1 个答案:

答案 0 :(得分:0)

property不是scope object,不能以这种方式与$compile一起使用。相反,你可以这样做:

var strHtml = $compile('<div><div class=\'hotelMarker\'>' +
            '<div class=\'hotelIcon\'>' +
            '<img alt=\'\' class=\'menuShadow\' src=\'' + property.PropertyThumbnail + '\'' +
            ' height=\'45\' width=\'45\'/>' +
            '</div>' +
            '<div class=\'hotelText\'>' +
            '<span class=\'hotelHeader\'>' + property.PropertyName + '&nbsp;' +
            '</span>' +
            '</div>' +
            '</div></div>')(scope);

有关工作示例,请参阅此Plunker