angularjs - 将自定义指令中的属性复制到输入

标签 angularjs

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

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

我想选择使用所有可能的 Angular 指令作为输入,如 ng-pattern、ng-minlength 等。现在它看起来像这样:
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>'
    };
}]);

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

我希望两者都工作:

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">

最佳答案

我给你三个答案。

  • 通常,不建议同时支持模型属性和直接支持字符串。此案例由 = 处理在你的指令范围内声明,如果你想传递一个字符串,你可以使用简单的引号。例如 ngBind 的工作方式是这样的:ng-bind="someModel"ng-bind="'some string'"
  • 如果你真的想,你可以尝试解析表达式。如果它是可解析的,则意味着它是一个范围模型。否则,它很可能是一个字符串。请参阅以下代码片段中的工作示例:


  • 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>


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


  • 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>

    关于angularjs - 将自定义指令中的属性复制到输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28392559/

    相关文章:

    javascript - AngularJS onload - 未捕获的 ReferenceError : $scope is not defined

    javascript - 如何在 AngularJS 上触发另一个 Controller ?

    javascript - 如何在 AngularJS 中选中和取消选中复选框时运行函数?

    javascript - Angular 模块需要定义两次

    angularjs - 如何在显示新的 toastr 之前清除以前的 toastr 并在它们之间设置超时?

    javascript - 未知提供商 : pagingParamsProvider <- pagingParams In ResultAnalysisDetailController

    javascript - 文件上传: View is not updating on non angular event

    jquery - AngularJS 比 jQuery 有什么优势?

    html - CSS滑入滑出动画溢出问题

    angularjs - 使用 ng-click 的 md-autocomplete 模板无法阻止选择