2017-02-15 56 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