dynamically adding directives in ng-repeat

前端 未结 3 1708
北恋
北恋 2020-12-08 05:24

I am trying to dynamically add different directives in an ng-repeat however the output is not being interpreted as directives.

I\'ve added a simple example here: htt

3条回答
  •  庸人自扰
    2020-12-08 05:41

    i faced with the same problem in one of my projects and you can see how i solve this problem on jsfiddle

    HTML:

    Page

    JS:

    var app = angular.module('app',[]);
    app.controller('mainCtrl', ['$scope', '$q', 'widgetAPI', function($scope, $q, widgetAPI) {
    $scope.widgets = [];
    widgetAPI.get().then(
        function(data) {
            $scope.widgets = data;
        },
        function(err) {
            console.log("error", err);
        }
    );}])
    
    .service('widgetAPI', ['$q', function($q) {
    var api = {};
    api.get = function() {
        //here will be $http in real app
        return $q.when(
            [
                {
                    component: 'wgtitle',
                    title: "Hello world",
                    color: '#DB1F1F',
                    backgroundColor: '#c1c1c1',
                    fontSize: '32px'
                },
                {
                    component: 'wgimage',
                    src: "http://cs425622.vk.me/v425622209/79c5/JgEUtAic8QA.jpg",
                    width: '100px'
                },
                 {
                    component: 'wgimage',
                    src: "http://cs425622.vk.me/v425622209/79cf/S5F71ZMh8d0.jpg",
                    width: '400px'
                }
    
            ]
        );
    };
    return api;}])
    
    .directive('proxy', ['$parse', '$injector', '$compile', function ($parse, $injector, $compile) {
    return {
        replace: true,
        link: function (scope, element, attrs) {
            var nameGetter = $parse(attrs.proxy);
            var name = nameGetter(scope);
            var value = undefined;
            if (attrs.proxyValue) {
              var valueGetter = $parse(attrs.proxyValue);
              value = valueGetter(scope);
            }
    
            var directive = $injector.get(name.component + 'Directive')[0];
            if (value !== undefined) {
                attrs[name.component] = value;
            }
            var a = $compile(directive.template)(scope);
            element.replaceWith(a);
        }
    }}])
    
    .directive('wgtitle', function() {
    return {
        restrict: 'A',
        scope: true,
        replace: true,
        template: '

    {{widget.title}}

    ', link: function(scope, element, attrs) { } }}) .directive('wgimage', function() { return { restrict: 'A', scope: true, replace: true, template: '', link: function(scope, element, attrs) { } }});

    I hope it will usefull.

提交回复
热议问题