2014-11-24 86 views
2

我需要動態地輸入字段需要(或不),並希望在指令中設置此值。我知道有ng-required指令,可以設置爲ng-required =「datamodel.required」,但最終,我想在指令中拉一個設置對象,並根據該配置打開/關閉所需的參數。配置是在一個服務中,我不想爲每個表單控制器注入服務 - 因此我需要在一個指令中設置它。AngularJS設置輸入要求在指令

這裏是一個的jsfiddle起點: http://jsfiddle.net/hm2b771z/2/

app.directive('requiredConfig', function($compile){ 
    return { 
     link: function(scope, element, attrs){ 
      console.log(attrs.requiredConfig); 
      console.log(attrs.ngRequired); 
      attrs.ngRequired = (attrs.requiredConfig == "true") ? true : false; 
      $compile(element.contents())(scope); 
      console.log(attrs.ngRequired); 
      console.log('_______________________'); 
     } 
    } 
}); 

我想到的是,是,而第二個可選仍然被要求在第一場選擇的領域。

謝謝!取而代之的

attrs.required = (attrs.requiredConfig == "true") ? true : false; 

+0

找到我的答案在這裏:http://stackoverflow.com/questions/21687925/angular-directive-how-to-add-an-attribute-to-the-element – snazzyHawk 2014-11-24 04:25:29

+2

如果你的問題是重複的,我建議刪除它。否則,最好回答自己的問題,如何讓別人爲你回答。 (即不僅僅是一個鏈接) – 2014-11-24 04:53:56

回答

0

使用

if (attrs.requiredConfig == "true"){ 
    element.attr('required', 'true'); 
} 
0

這裏就是我最後做得益於Angular directive how to add an attribute to the element?

angular.module('app') 
.directive 
(
    'requiredByConfig', 
    function($compile, Utils){ 
     var directive = { 
      terminal: true, 
      priority: 1001, 
      compile: function(element, scope){ 
       var configKey = element.attr('required-by-config'); 
       var req = Utils.getRequiredFromConfig(configKey) // Injected; 

       // Remove this directive in order to avoid infinite compile loop. 
       element.removeAttr('required-by-config'); 

       // Add the required directive with the required value. 
       element.attr('ng-required', req); 

       // Compile the new directive 
       $compile(element.contents())(scope); 

       var fn = $compile(element); 
       return function(scope){ 
        fn(scope); 
       }; 
      } 
     }; 

     return directive; 
    } 
); 

然而,一個更好的解決方案WA s到使用過濾器:

angular.module('app').filter 
('requiredByConfig', 
    function(Utils){ 
     return function(initialValue, configKey, visible){ 
      if(angular.isDefined(visible) && !visible){ 
       // If the input is hidden, we don't want to require it. 
       return false; 
      } 

      // Get the config setting. If available, overwrite the default. 
      if(angular.isDefined(Utils.SETTINGS[ configKey ])){ 
       // A config exists for this field. Return the value of the config. 
       return Utils.getBoolean(Utils.SETTINGS[ configKey ]); 
      } else { 
       // Return the initial required value 
       return initialValue; 
      } 
     } 
    } 
)