2016-01-21 59 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