2017-02-15 26 views
2

我有多次使用的组件,有58次被删除。唯一不同的是添加验证的唯一属性。我想要做的是在编译之前向我的模板添加一组属性。当使用Angular组件时,这可能实现吗?在Angular预编译的组件上动态添加属性

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" /> 

当我使用的组件<component input-attributes="directive1, directive2"></component>它不会呈现出我的字符串,即使它,我不会相信它会工作。那么是否有一种方法可以动态地设置AngularJS中的属性?

回答

0

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

0

这是角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" /> 

https://www.thinkingmedia.ca/2015/03/conditionally-add-a-html-element-attribute-value-in-angularjs/

编辑:它可能不会是干净的,但你可以创建一个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)); 
    } 
} 
}); 

然后在DOM

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

小提琴:http://jsfiddle.net/brhardwick/nx16zdrL/1/

+0

这是角1,他们指出的方式是我们今天解决它的方式。我们有85个指令,所以这不是一个好的解决方案。 – user1969907

+0

检查我的编辑。您可能需要调整指令是否复杂。但这应该让你去 – brhardwick