2016-02-10 26 views
0

我需要知道是否有可能,並在是的情況下如何做到這一點。包裝divs輸入指令

我已經輸入我的形式是這樣的:

<input type="text" class="form-control" name="dirinput" 
     placeholder="Placeholder" 
     translate 
     translate-attr-placeholder="{{ placeholder }}" 
     ng-model-options="{ debounce: 500 }"> 

我想,解決這個輸入,包的div管理標籤,如果有錯誤(如顯示錯誤的情況下,一個字符串) 。 我還需要能夠在指令輸入元素。

在我已經寫這些代碼的每個輸入

 <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6"> 
      <div class="form-group label-static" 
       ng-class="{ 'has-error': relatedForm.first_name.$invalid && relatedForm.first_name.$dirty, 
       'has-success' : relatedForm.first_name.$valid }"> 
       <label for="input-first_name" 
         class="control-label" translate> 
        FIRST_NAME 
       </label> 
       <input type="text" class="form-control" 
         id="input-first_name" name="first_name" 
         placeholder="First name" 
         ng-model="relatedCtrl.data.first_name" 
         ng-model-options="{ debounce: 500 }" 
         required autofocus> 
       <p class="help-block" 
        ng-if="relatedForm.first_name.$error.required" translate> 
        ERR_FIRST_NAME_REQUIRED 
       </p> 
      </div> 
     </div> 

如果你可以看到有很多「重複」的代碼的那一刻,我徘徊,如果要避免這種情況成爲可能。

非常感謝

+0

當然可以,而且也應該用一個指令,但你不能真正「包裝」周圍的其他對象的指令(據我所知)。相反,創建一個指令並傳入參數來填充動態數據(例如輸入名稱,型號名稱等) – Seonixx

+0

您可以向我展示一個示例嗎? – Stefano

回答

0

您可以使用角指令的transclude特點:

myModule.directive('myInput', function() { 
    return { 
    transclude: true, 
    templateUrl: 'my-transclude.html' 
    }; 
}); 

my-transclude.html

<div class="wrapper> 
    <div ng-transclude></div> 
</div> 

在HTML:

<my-input> 
    <input type="text" class="form-control" name="dirinput" 
     placeholder="Placeholder" 
     translate 
     translate-attr-placeholder="{{ placeholder }}" 
     ng-model-options="{ debounce: 500 }"> 
</my-input> 

參考:Angular directives

當然,你可以使用template,而不是直接templateUrl沒有額外的HTML文件,但templateUrl的採取一個很好的做法。

0

是的,您可以創建包含輸入的transclude指令。

關於jsfiddle的示例。

var myApp = angular.module("myApp", []); 
 

 

 
myApp.controller("myCtrl", function($scope) { 
 

 
}); 
 

 

 
myApp.directive("wrapExample", function() { 
 
    return { 
 
    restrict: 'E', 
 
    transclude:true, 
 
    scope: { 
 
     proccess: "=", 
 
    }, 
 
    template:'<div><label>I\'m before wrapped label</label><div ng-transclude></div><div>I\'m after wrapped div</div></div>', 
 
    link: function(scope, element, attrs) { 
 
    }, 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<body ng-app="myApp" ng-controller="myCtrl"> 
 
    <wrap-example> 
 
    <input value="input" /> 
 
    </wrap-example> 
 
</body>

+0

是否可以將自定義指令添加到輸入元素?就像數據的自定義驗證 – Stefano

+0

對不起,我不知道) –