将自定义指令中的属性复制到输入 [英] Copy attributes from custom directive to input

查看:28
本文介绍了将自定义指令中的属性复制到输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义驱动程序,它用 div 包装输入并添加一个标签.

我想对输入使用可选的所有可能的角度指令,例如 ng-pattern、ng-minlength 等.现在看起来像这样:

app.directive('myInput',[function () {返回 {限制:E",替换:真的,范围: {ngModel: '=',姓名: '@',ngMinlength: '=',ngMaxlength: '=',ngPattern: '@',标签: '@'},编译:函数(元素,属性){if(!_.isUndefined(attrs['ngMinlength'])) {element.find('input').attr('ng-minlength', 'ngMinlength');}if(!_.isUndefined(attrs['ngMaxlength'])) {element.find('input').attr('ng-maxlength', 'ngMaxlength');}if(!_.isUndefined(attrs['ngPattern'])) {element.find('input').attr('ng-pattern', attrs['ngPattern']);}},模板:'<div class="form-group">'+ '<标签>{{ 标签 |翻译}}</label>'+ '

'+ '<input type="text" class="form-control input-sm" name="{{ name }}" ng-model="ngModel">'+ '</div></div>'};}]);

问题是我想在输入中使用与 ng-pattern 完全相同的 ng-pattern,所以我希望有可能在 ng-pattern 中使用 regexp 以及具有模式的范围变量 ($scope.mypattern =/^[az]+$/; ... ng-pattern="mypattern").如何管理?

我想要两个都工作:

1.

2.

$scope.myPattern =/^[a-z]+$/...<my-input label="My Label" name="myname" ng-model="mymodel" ng-pattern="myPattern">

解决方案

我给你三个答案.

  1. 一般来说,不建议同时支持模型属性和直接支持字符串.这种情况由指令范围内的 = 声明处理,如果您想传递一个字符串,您将使用简单的引号.例如 ngBind 的工作方式如下:ng-bind="someModel"ng-bind="'some string'"

  2. 如果您真的想,您可以尝试解析表达式.如果它是可解析的,则意味着它是一个范围模型.否则,它很可能是一个字符串.请参阅以下代码片段中的工作示例:

angular.module('test', []).controller('test', function($scope) {$scope.model = "范围模型中的字符串";}).directive('turlututu', function($parse) {返回 {限制:'E',范围: {},模板:'<div class="tu">{{content}}</div>',链接:功能(范围,元素,属性){尝试 {scope.content = $parse(attrs.text)(scope.$parent);} 抓住(错误){} 最后 {如果(!范围.内容){scope.content = attrs.text;}}}};});

body { font-family: monospace;}.tu { 填充:10px;边距:10px;背景:#f5f5f5;边框底部:2px 实心 #e5e5e5;}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><div ng-app="test" ng-controller="test"><turlututu text="硬编码字符串"></turlututu><turlututu text="model"></turlututu>

  1. 在ngPattern的情况下,因为代码中的好奇心总是会帮助你,你可以在Angular的源代码中看到他们测试了属性第一个字符:如果是/,它被认为是一个正则表达式,否则是范围模型(参见下面的示例)

angular.module('test', []).controller('test', function($scope) {$scope.model =/[a-z]*/;}).directive('turlututu', function($parse) {返回 {限制:'E',范围: {},模板:'<div class="tu">{{content}}</div>',链接:功能(范围,元素,属性){if (attrs.regexp.charAt(0) === '/') {scope.reg = new RegExp( attrs.regexp.substring(1, attrs.regexp.length-1) );} 别的 {scope.reg = new RegExp( $parse(attrs.regexp)(scope.$parent));}scope.content = scope.reg.toString()}};});

body { font-family: monospace;}.tu { 填充:10px;边距:10px;背景:#f5f5f5;边框底部:2px 实心 #e5e5e5;}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><div ng-app="test" ng-controller="test"><turlututu regexp="/[0-9]*/"></turlututu><turlututu regexp="model"></turlututu>

I have a custom driective which wraps input with div and adds a label.

<my-input label="My Label" name="myname" ng-model="mymodel" ng-pattern="/^[a-z]+$/">

I want to use optionally all of possible angular directives for input like ng-pattern, ng-minlength etc. Now it looks like this:

app.directive('myInput',[function () {
    return {
        restrict: "E",
        replace: true,
        scope: {
            ngModel: '=',
            name: '@',

            ngMinlength: '=',
            ngMaxlength: '=',
            ngPattern: '@',                
            label: '@'                
        },
        compile: function(element, attrs){

            if(!_.isUndefined(attrs['ngMinlength'])) {
                element.find('input').attr('ng-minlength', 'ngMinlength');
            }
            if(!_.isUndefined(attrs['ngMaxlength'])) {
                element.find('input').attr('ng-maxlength', 'ngMaxlength');
            }                
            if(!_.isUndefined(attrs['ngPattern'])) {
                element.find('input').attr('ng-pattern', attrs['ngPattern']);
            }               


        },
        template: '<div class="form-group">'
        + '<label>{{ label | translate }}</label>'
        + '<div>'
        + '<input type="text" class="form-control input-sm" name="{{ name }}" ng-model="ngModel">'           
        + '</div></div>'
    };
}]);

The problem is that I want use ng-pattern exactly the same as ng-pattern works in input, so I want to have possibility to use regexp in the ng-pattern and also scope variable with pattern ($scope.mypattern = /^[a-z]+$/; ... ng-pattern="mypattern"). How to manage this?

I want both working:

1.

<my-input label="My Label" name="myname" ng-model="mymodel" ng-pattern="/^[a-z]+$/">

2.

$scope.myPattern = /^[a-z]+$/
...
<my-input label="My Label" name="myname" ng-model="mymodel" ng-pattern="myPattern">

解决方案

I have three answers for you.

  1. In general, it is not recommended to support both a model property, and directly a String. This case is handled by a = declaration in your directive scope, and if you want to pass a String, you would use simple quotes. For instance ngBind works like this: ng-bind="someModel" or ng-bind="'some string'"

  2. If you really want to, you can try to parse the expression. If it is parsable, it means it is a scope model. Otherwise, it is likely a string. See working example in the code snippet below:

angular.module('test', [])

.controller('test', function($scope) {
  $scope.model = "string from scope model";
})

.directive('turlututu', function($parse) {
 return {
   restrict: 'E',
   scope: {},
   template: '<div class="tu">{{content}}</div>',
   link: function(scope, elem, attrs) {
     try {
       scope.content = $parse(attrs.text)(scope.$parent);
     } catch(err) {
     } finally {
       if (!scope.content) {
         scope.content = attrs.text;
       }
     }
   }
 };
});

body { font-family: monospace; }

.tu { padding: 10px; margin: 10px; background: #f5f5f5; border-bottom: 2px solid #e5e5e5; }

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="test">
  
  <turlututu text="hardcoded string"></turlututu>
  <turlututu text="model"></turlututu>
  
</div>

  1. In the case of ngPattern, because curiosity in code will always help you, you can see in the source code of Angular that they test the attribute first character: if it is / it is considered a regexp, otherwise a scope model (see example below)

angular.module('test', [])

.controller('test', function($scope) {
  $scope.model = /[a-z]*/;
})

.directive('turlututu', function($parse) {
 return {
   restrict: 'E',
   scope: {},
   template: '<div class="tu">{{content}}</div>',
   link: function(scope, elem, attrs) {
     if (attrs.regexp.charAt(0) === '/') {
       scope.reg = new RegExp( attrs.regexp.substring(1, attrs.regexp.length-1) );
     } else {     
       scope.reg = new RegExp( $parse(attrs.regexp)(scope.$parent) );
     }
     
     scope.content = scope.reg.toString()
   }
 };
});

body { font-family: monospace; }

.tu { padding: 10px; margin: 10px; background: #f5f5f5; border-bottom: 2px solid #e5e5e5; }

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="test">
  
  <turlututu regexp="/[0-9]*/"></turlututu>
  <turlututu regexp="model"></turlututu>
  
</div>

这篇关于将自定义指令中的属性复制到输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆