как добавить динамический элемент (шаблон) в угловой

0

Шаблон добавляет содержимое динамически со значением и цветом, как показано ниже, с использованием углового. Динамически создавать DOM-элемент из исходного значения с помощью предопределенных шаблонов.

Изображение 174551

Какие элементы используются в угловых js?

  1. директива
  2. шаблон

Как отсортировать директиву в угловом JS, используя Jquery ui sortable?

.directive('contentItem',function($compile){
    var imageTemplate = '<div class="mypanel mypanel-default portlet" ng-class="{fullscreen : fullscreen}" ng-show="close">'+
                '<div class="mypanel-heading">'+
                    '<div class="mypanel-btn" >'+
                        '<a href="" class="mypanel-fullscreen" tooltip="{{tooltipfullscreen}}" ng-click="toggleFullscreen()"><i class="{{fullscreenicon}}"></i></a>'+
                        '<a href="" class="mypanel-minimize"  ng-click="toggle()" tooltip="{{tooltipminimize}}"><i class="{{minimizeicon}}"></i></a>'+
                        '<a href="" class="mypanel-close tooltips" data-toggle="tooltip" title="Close Panel" tooltip="Close" ng-click="toggleHide()"><i class="fa fa-times"></i></a>'+
                    '</div>'+
                    '<h5 class="mypanel-title">Optional Sizes</h5>'+
                '</div>'+
                '<div class="mypanel-body" ng-show="on">'+
                    '<div id="area-chart" class="height300">'+
                    '</div>'+
             '</div>'+
            '</div>';



var getTemplate = function(contentType) {

        var template = '';

        switch(contentType) {
            case 'image':
                template = imageTemplate;
                break;
            case 'video':
                template = imageTemplate;
                break;
            case 'notes':
                template = imageTemplate;
                break;
        }

        return template;
    }

    var linker = function(scope, element, attrs) {
        scope.on = true;
        scope.tooltipminimize = 'Minimize';
        scope.minimizeicon = 'fa fa-minus';
        scope.fullscreenicon = 'fa fa-expand';
        scope.tooltipfullscreen = 'Fullscreen';
        scope.fullscreen = false;
        scope.close = true;
        scope.toggle = function () {
                scope.on = !scope.on;
                if(scope.tooltipminimize == 'Minimize'){
                    scope.minimizeicon = 'fa fa-plus';
                    scope.tooltipminimize = 'Maximize';
                }
                else{
                    scope.tooltipminimize = 'Minimize';
                    scope.minimizeicon = 'fa fa-minus';
                }
        };
        scope.toggleHide = function () {
                scope.close = !scope.close;
        };
        scope.toggleFullscreen = function(){
            scope.fullscreen = !scope.fullscreen;
            if(scope.tooltipfullscreen == 'Fullscreen'){
                    scope.fullscreenicon = 'fa fa-compress';
                    scope.tooltipfullscreen = 'Exit Fullscreen';
                }
                else{
                    scope.fullscreenicon = 'fa fa-expand';
                    scope.tooltipfullscreen = 'Fullscreen';
                }
        };
        scope.sortableOptions = {
        connectWith: '.sortable',
        item: '.portlet',
        placeholder: 'placeholder',
        dropOnEmpty: true
        };
        scope.rootDirectory = 'images/';
        element.html(getTemplate('image')).show();
        $compile(element.contents())(scope);
    }
    return{
        restrict: "E",
        link: linker,
        scope:true
    };
});
  • 0
    как скомпилировать?
Теги:
dom
angularjs-scope
angularjs-directive

1 ответ

1

Это определенно случай для директивы. Перейдите в свои аргументы и используйте функцию ссылки, чтобы в основном создать шаблон из строк. В приведенном ниже примере я беру параметры для создания входных данных для формы.

    .directive('qrunChild', ['$compile', function ($compile) {
    return {
        restrict: 'AE',
        require: 'ngModel',
        scope: {
            ngModel: '=',
        },
        link: function (scope, element, iAttrs, ngModelController) {

            var tpl = '';
            var bpstart = '<div class="row no-margin">';
            var bp = '&nbsp;&nbsp;<span class="pull-left"><i class="fa fa-circle text-xs text-info-lt m-r-xs pull-left"></i>{{ngModel.name}}</span><span class="badge pull-right">{{ngModel.type}}</span>';
            var bpend = '</div class="row">';
            if (scope.ngModel.type == 'text') {
                //tpl = '<input type="text" ng-model="ngModel.type">';
            }
            else if (scope.ngModel.type == 'mc') {
                tpl = '<div ng-repeat="opt in ngModel.options"><label class="ui-checks option"><input type="radio" ng-model="ngModel.optionsSelected" value="{{opt.name}}"><i style="margin-right:20px;"></i>{{opt.name}}</label></div>';
            }

            view = $compile(bpstart + bp + tpl + bpend)(scope);
            return $(element).html(view);

        }
    };
}])

Я мог бы назвать это следующим образом в своем HTML:

Изменение: если вы хотите указать URL-адрес шаблона, вы можете сделать что-то вроде этого (в этом случае он просто принимает аргумент, называемый item.templateUrl в родительской области):

.directive('dynamicTemplate', function () {
    return {
        template: '<ng-include src="getTemplateUrl()"/>',
        scope: false,
        transclude: true,
        restrict: 'E',
        controller: function ($scope) {
            $scope.getTemplateUrl = function () {
                //resolve the template
                return $scope.item.templateUrl;
            }
        }
    };
})
  • 0
    Можете ли вы объяснить мою обновленную очередь?

Ещё вопросы

Сообщество Overcoder
Наверх
Меню