2016-02-10 141 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

对不起,我不知道) –