angular根据scope属性创建元素

angular Create element based on scope attribute

本文关键字:创建 元素 属性 scope 根据 angular      更新时间:2023-09-26

我如何控制一个指令的模板基于$scope变量已经被评估(编译?)由angular?

例如,当$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>

在这个例子中,我希望元素类型(input, textarea, checkbox等)由一个动态的$scope属性控制。

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

演示

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>

app.js

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
    $scope.inputs = {
        one    : 'text',
        two    : 'checkbox',
        three  : 'textarea'
    };
});
app.directive('inputTypeDir', function(){
    return {
        restrict: 'E',
        scope: {
            inputType: '='
        },
        templateUrl: 'template.html'
    }
});

template.html

<input ng-if="inputType !== 'textarea'" type="{{inputType}}">
<textarea ng-if="inputType === 'textarea'" cols="30" rows="10"></textarea>

或者,如果你不想创建一个孤立的作用域,如果你只需要传递字符串值,你可以直接访问link函数中的属性:

<input-type-dir  foo="text"></input-type-dir>
<input-type-dir  foo="checkbox"></input-type-dir>
<input-type-dir  foo="textarea"></input-type-dir>

指令def

link: function(scope, el, attrs){ 
    scope.foo = attrs.foo;
}

tempalte

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