Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 在角度预编译中动态添加组件属性_Angularjs_Angular Components - Fatal编程技术网

Angularjs 在角度预编译中动态添加组件属性

Angularjs 在角度预编译中动态添加组件属性,angularjs,angular-components,Angularjs,Angular Components,我有一个被多次使用的组件,58次被测试。它们之间唯一不同的是添加验证的唯一属性。我想做的是在编译之前向模板添加一个属性数组。当使用角度组件时,这是否可能实现 component.js (function () { 'use strict'; angular .module('upaApp') .component('component', { bindings: { inputAttribu

我有一个被多次使用的组件,58次被测试。它们之间唯一不同的是添加验证的唯一属性。我想做的是在编译之前向模板添加一个属性数组。当使用角度组件时,这是否可能实现

component.js

(function () {
    'use strict';

    angular
        .module('upaApp')
        .component('component', {
            bindings: {
                inputAttributes: '@',
            },
            controller: controller,
            restrict: 'E',
            templateUrl: 'app/component/component.html'
        });

    function controller() {
        var $ctrl = this;
    }
})();
component.html

<input {{ $ctrl.inputAttributes }}
       class="form-control"
       type="text" />

当我使用组件
时,它不会显示我的字符串,即使它显示了,我也不能确定它是否能工作。那么有没有一种方法可以动态地设置AngularJS中的属性呢?

这是角度1还是角度2? 我假设是前者

我不知道如何将字符串作为属性。作为一种解决方法,您可以有条件地使用ng attr-属性插入属性。如果变量未定义,这将插入属性。 也许是这样的:

$scope.ctrl.inputAttributes = {
    directive1:undefined, //this one wont show 
    directive2:"this one will show"// as directive2="this one will show"
}
然后在标记中:

<input ng-attr-directive1="ctrl.inputAttributes.directive1"
       ng-attr-directive2="ctrl.inputAttributes.directive2"
       class="form-control"
       type="text" />

编辑:它可能不干净,但您可以创建一个编译html的指令

app.directive('dynamicAttributes', function ($compile) {
return {
    restrict: 'E',
    scope: {
        attributes: '@'
    },
    link: function (scope, elem, attrs) {
        var h = '<input '+scope.attributes + ' class="form-control" type="text" />';
        elem.replaceWith($compile(h)(scope));
    }
}
});
app.directive('dynamicAttribute',函数($compile){
返回{
限制:'E',
范围:{
属性:'@'
},
链接:功能(范围、要素、属性){
var h='';
替换为($compile(h)(范围));
}
}
});
然后在你的家里

<dynamic-attributes attributes="1 2 3"></dynamic-attributes>


小提琴手:

实际上我的问题有一个非常简单的解决方案。您可以使用ng模型将值发送到组件。当我将指令放在组件上时,它会相应地进行验证,因为它可以访问ng模型中的值。

这是角度1,您指出的方式就是我们今天解决它的方式。我们有85条指令,所以这不是一个好的解决方案。请检查我的编辑。如果指令很复杂,您可能需要调整。但这应该能让你走了