【问题标题】:Dynamically including directive in an AngularJS partial在 AngularJS 部分中动态包含指令
【发布时间】:2014-04-29 00:26:50
【问题描述】:

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

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

示例 JSON:

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

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

【问题讨论】:

    标签: javascript angularjs partials


    【解决方案1】:

    针对作用域使用 $compile 服务。这将允许您编译可以附加到容器的角度代码。

    见 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 指令只是创建指令,就好像它是元素的属性一样。这是一个非常简单的示例,但应该可以帮助您开始您想要做的事情,您可以相应地更新构建元素/指令的逻辑。

    【讨论】:

    • 感谢 Patrick 的解决方案,我正在寻找与您的解决方案类似的东西。
    猜你喜欢
    • 2013-12-31
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 2013-07-24
    • 2017-05-27
    • 1970-01-01
    相关资源
    最近更新 更多