2014-11-24 5 views
2

동적으로 입력 필드를 필요로하거나 만들 필요가 있고 지시어에이 값을 설정하려고합니다. 필요한 지시문이 있고 ng-required = "datamodel.required"로 설정할 수 있지만 궁극적으로 지시문에서 설정 개체를 가져 와서 해당 구성을 기반으로 필요한 매개 변수를 설정/해제하고 싶습니다. 구성은 서비스에 있으며 각 폼 컨트롤러에 서비스를 주입하고 싶지 않습니다. 따라서 지시문에서이 설정을해야하는 이유는 무엇입니까? http://jsfiddle.net/hm2b771z/2/지시문에 AngularJS Set 입력 필요

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('_______________________'); 
     } 
    } 
}); 

는 내가 기대하는 것은 두 번째는 선택 남아있는 동안해야 할 첫 번째 필드의 옵션입니다 필드 :

는 여기 JSFiddle의 출발점입니다.

감사합니다.

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을 :

+0

찾을 여기 내 대답 : http://stackoverflow.com/questions/21687925/angular-directive-how-to-add-an-attribute-to-the-element – snazzyHawk

+2

만약의 필터를 사용하는 방법 귀하의 질문은 중복, 나는 그것을 삭제하는 것이 좋습니다. 그렇지 않으면 자신의 질문에 다른 사람이 대답하기를 원하는 방식으로 대답하는 것이 좋습니다. (즉, 링크가있는 것은 아닙니다) –

답변

0

대신

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

의 사용은 여기

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

내가 Angular directive how to add an attribute to the element?에 감사하고 결국 무엇

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; 
      } 
     } 
    } 
) 
관련 문제