2017-02-15 11 views
2

私は、複数回使用されるコンポーネントを持っており、58回が実行されます。それらの間で異なる唯一のものは、バリデーションを追加するためのユニークな属性です。私がしたいのは、コンパイルする前に、テンプレートに属性の配列を追加することです。これは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/

EDIT:それはきれいではないかもしれないが、あなたがHTMLをコンパイルディレクティブを作成することができます。あなたのDOMで、その後

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)); 
    } 
} 
}); 

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

フィドル:http://jsfiddle.net/brhardwick/nx16zdrL/1/

+0

これは角度1であり、あなたが指摘したところでは、それが今日解決した方法です。私たちは85の指令を持っているので、良い解決策ではありません。 – user1969907

+0

私の編集をチェックしてください。ディレクティブが複雑な場合は、調整が必要な場合があります。しかし、これはあなたに行く必要があります – brhardwick

関連する問題