Javascript 基于范围属性创建元素

Javascript 基于范围属性创建元素,javascript,angularjs,Javascript,Angularjs,如何基于已由angular计算(编译?)的$scope变量控制指令的模板 例如,由于$scope,这将不起作用 app.directive('inputType', function(){ var template; if ($scope.inputType === 'input') { template = "<input ng-attr-my-attribute='" + $scope.myAttribute + "' />"; }

如何基于已由angular计算(编译?)的$scope变量控制指令的模板

例如,由于$scope,这将不起作用

app.directive('inputType', function(){
    var template;

    if ($scope.inputType === 'input') {
         template = "<input ng-attr-my-attribute='" + $scope.myAttribute + "' />";
    }

    return {
        restrict: 'E',
        scope: {
            inputType: '=',
            myAttribute: '='
        },
        template: template
    }    
})

<inputType inputType="input" my-attribute="some value"></inputType>
app.directive('inputType',function(){
var模板;
如果($scope.inputType=='input'){
模板=”;
}
返回{
限制:'E',
范围:{
输入类型:'=',
myAttribute:“=”
},
模板:模板
}    
})

在本例中,我希望元素类型(输入、文本区域、复选框等)由动态
$scope
属性控制。

您将在模板中执行所有条件标记,并且您可以将该逻辑基于来自父控制器的双向绑定范围变量。此外,您还没有在HTML中正确使用you指令。您需要在标记中定义camel case和usesnake case中的指令。试试这个

index.html

<body ng-controller="MainCtrl">
    <input-type-dir  input-type="inputs.one"></input-type-dir>
    <input-type-dir  input-type="inputs.two"></input-type-dir>
    <input-type-dir  input-type="inputs.three"></input-type-dir>
</body>
<input ng-if="inputType !== 'textarea'" type="{{inputType}}">
<textarea ng-if="inputType === 'textarea'" cols="30" rows="10"></textarea>
template.html

<body ng-controller="MainCtrl">
    <input-type-dir  input-type="inputs.one"></input-type-dir>
    <input-type-dir  input-type="inputs.two"></input-type-dir>
    <input-type-dir  input-type="inputs.three"></input-type-dir>
</body>
<input ng-if="inputType !== 'textarea'" type="{{inputType}}">
<textarea ng-if="inputType === 'textarea'" cols="30" rows="10"></textarea>
tempalte

<input ng-if="foo !== 'textarea'" type="{{foo}}">


在HTML中定义
模板
变量应该适合您。比如,“挑战是从它自己的范围中获取html
<input ng-if="foo !== 'textarea'" type="{{foo}}">