在AngularJS的分部中动态包含指令

Dynamically including directive in an AngularJS partial

本文关键字:动态 包含 指令 AngularJS      更新时间:2023-09-26

我有一个指令列表(通常是表单字段和自定义表单控件)。现在,我将从后端获取指令名称列表,以用于构建表单。

它基本上创建了一个动态表单,我不知道表单中所有的表单字段是什么(这取决于我从后端获得的JSON配置文件)。

示例JSON:

field1 : {
     type: 'text',
     directive : 'directive1'
},
field2: {
     type : 'dropdown',
     directive : 'dropdown-directive'
}

我能在AngularJS中做类似的事情吗?如果可能的话,怎么做?

针对作用域使用$compile服务。这将允许你编译可以添加到容器中的angular代码。

参见jsfiddle: http://jsfiddle.net/p8jjZ/1/

HTML:

<div ng-app="myApp" ng-controller="MainController">
    <div custom-elements="myData.elements"></div>
    <p>{{user}}</p>
</div>
JavaScript:

var mod = angular.module("myApp", []);
mod.controller("MainController", function ($scope) {
    $scope.myData = {};
    $scope.myData.elements = {
        field1 :{ type: 'text', directive : 'directive1' },
        field2: { type : 'dropdown', directive : 'dropdown-directive' }
    }; 
});
mod.directive("customElements", function ($compile) {
    return {
        restrict: "A",
        scope: {
            customElements: "="
        },
        link: function (scope, element, attrs) {
            var prop,
                elems = scope.customElements,
                currElem,
                compiled;
            for (prop in elems) {
                currElem = elems[prop];
                console.log("Working on " + prop);
                //compile input against parent scope. Assuming directives are attributes, but adapt to your scenario:
                compiled = $compile('<div ' + currElem.directive + '></div>')(scope.$parent);
                //append this to customElements
                element.append(compiled);
            }
        }
    }
});
mod.directive("directive1", function () {
    return {
        restrict: "A",
        template: '<div>Whoa! I am directive 1<br><input type="text" ng-model="user.name"></div>'
    }
});
mod.directive("dropdownDirective", function () {
    return {
        restrict: "A",
        template: '<div>I am another directive<br><select ng-model="user.color"><option value="blue">blue</option><option value="green">Green</option></div>'
    }
});

customElement指令只是创建了一个指令,就好像它是一个元素的属性一样。这是一个非常简单的例子,但应该让你开始做你想做的事情,你可以更新相应的逻辑来构建元素/指令。