2016-05-15 36 views
0
这一切

首先是我的plunker:https://plnkr.co/edit/JbG6vlSbeWrBcmYhmhF1?p=preview试图与角1.4.9定制指令,但坚持了链接功能

我试图让指令添加浮动标签如本example任何输入领域。

例如我有以下输入字段:

<input floating-label placeholder="Better field" type="text" class="form-control" ng-model="floatingDirective"/> 

floating-label应该以这样的方式工作,这将扩大到下面的代码:

<div class="field"> 
     <label ng-show="betterField" class="show-hide">Better field</label> 
     <input type="text" class="form-control" ng-model="betterField" placeholder="Better field"/> 
</div> 

我不能做到这一点,这是我的指令,目前为止:

.directive('floatingLabel', function ($compile) { 
     return { 
      restrict: 'A', 
      require: 'ngModel', 
      scope: { 
       ngModel: '=' 
      }, 
      link: function(scope, element, attrs, ctrl, transclude) { 
       var wrapper = '<div class="field">' + 
           '</div>'; 

       element.after($compile('<label ng-show="' + attrs.ngModel + '" class="show-hide">' + attrs.placeholder + '</label>')(scope)); 
       element.wrap(wrapper); 
      } 
     }} 
) 

无法实现如何组合wrapprependappend以获得所需结构以及如何使ng-showng-model一起使用的值。

预先感谢您。

回答

1

我会建议做一个轻微的重组,使其工作plunkr

我认为您的指令应该处理创建输入和标签,以便您不必担心链接功能,并且您可以更好地控制范围。这应该是这样的......

angular.module('baseapp.directives',[]) 
angular.module('baseapp.directives') 
.directive('floatingLabelInput', function(){ 
     return { 
      restrict: 'E', 
      scope: { 
       ngModel: '=', 
       placeholder: '@' 
      }, 
      template: `<div class="field"><input floating-label placeholder="Better field" type="text" class="form-control" ng-model="ngModel"/><label ng-show="ngModel" class="show-hide">{{placeholder}}</label></div>` 
     } 
} 
) 

然后在你的HTML你只做到这一点...

<floating-label-input ng-model="floatingDirective" placeholder="Better field"></floating-label-input> 
+0

其实你的解决方案的工作,我想过这个问题,但我想这样做的一种我想要的方式,否则我们的团队应该做很多工作来替换所有的输入字段,另外还需要另外一个表单元素来做另一个指令。如果没有人会再提供,我会在几天内接受你的回答。 – Anatoly

相关问题