2016-01-21 60 views
0

我已经创建了一个带有一些输入的Angular指令元素,并且根据元素的属性,输入应该使用默认值进行设置。这里是指令:在角度指令中设置默认值输入

.directive('zoneType', ['$compile', function(){ 
    restrict: "E", 
    require: "^?ngModel", 
    templateUrl: "zone.html", 
    link: function(scope, element, attrs, ngModel){ 
     if(!ngModel) return; 

     var temp = 0; 
     var press = 0; 

     if(attrs.region=="top"){ 
      temp = 60; 
      press = 2; 
     }else if(attrs.region=="bottom"){ 
      temp = 20; 
      press = 0.4; 
     } 

     element.find("#gas1").val(temp); 
     element.find("#gas2").val(press); 

     ngModel.$setViewValue(element.html()); 
     ngModel.$render(); 
}]); 

和模板看起来像这样

<form role="form" class="form-inline"> 
      <div class="form-group"> 
       <input placeholder="Gas1" id="gas1" class="form-control" type="number" ng-model="$root.zone[$index].gas1"/> 
      </div> 
      <div class="form-group"> 
       <input placeholder="Gas2" id="gas2" class="form-control" type="number" ng-model="$root.zone[$index].gas2"/> 
      </div> 
     </form> 

的$指数是必要的,因为形式是角标签集内。

我声明了这样

<zone-type region='top' ng-model='zone'></zone-type> 

模板加载正确的元素,但值没有被设置,这是做正确的方式?

回答

0

试试这个:

.directive('zoneType', ['$compile', function() { 
      restrict: "E", 
      require: "^?ngModel", // <<<<< don't know if you need this. 
      templateUrl: "zone.html", 
      link: function(scope, element, attrs, ngModel) { 
       scope.temp = 0; 
       scope.press = 0; 

       if (attrs.region == "top") { 
        scope.temp = 60; 
        scope.press = 2; 
       } else if (attrs.region == "bottom") { 
        scope.temp = 20; 
        scope.press = 0.4; 
       } 
      }]); 

而且你的HTML应该是:

<form role="form" class="form-inline"> 
    <div class="form-group"> 
     <input placeholder="Gas1" id="gas1" class="form-control" type="number" ng-model="temp"/> 
    </div> 
    <div class="form-group"> 
     <input placeholder="Gas2" id="gas2" class="form-control" type="number" ng-model="press"/> 
    </div> 
</form> 

你真的不需要ID = “GAS1” 和id = “气2”,除非你有需要在你的代码中使用它们。 Angular会执行双向绑定,因为你有ng模型。 使用ng模型时,Angular会将temp绑定到任何scope.temp。

所以后来在你的代码中,如果你像temp.temp ='some value'那样改变临时值,那么这个值会自动显示在浏览器中,尽管你可能需要调用scope。$ apply()或scope。$ digest ()。

+0

它的工作原理!但是这个指令在其他选项卡中重复出现,我如何才能访问控制器中每个选项卡的“temp”和“press”? –

+0

该指令的范围如何定义。最好是将范围隔离开来,特别是当您计划在页面中多次出现相同的指令时。 – Will