2016-09-26 75 views
2

我有一个简单的表单,其中的字段是通过名为field的指令动态生成的。当我点击提交时,这些字段被验证并生成有效的类名,例如ng-invalid,ng-invalid-email。但表单的类名永远是ng-valid。任何帮助将非常感激!

Plnkr

HTML

<body ng-controller="app_controller"> 
    <form name="register" ng-submit="register_user()" novalidate> 
     <table> 
     <tr> 
      <td>Username: </td> 
      <td><field name="username" value="info"></field></td> 
     </tr> 
     <tr> 
      <td>Email: </td> 
      <td><field name="email" value="info"></field></td> 
     </tr> 
     <tr> 
      <td></td> 
      <td><input type="submit" value="submit" ng-disabled="register.$invalid" /></td> 
     </tr> 
     </table> 

     Invalid: {{ register.$invalid }} <br /> 
     valid: {{ register.$valid }} 
    </form> 

JS

var app = angular.module('app', []); 

app.controller('app_controller', function($rootScope, $scope) { 
    $scope.info = { 
    username: '', 
    email: '' 
    }; 

    $rootScope.meta = { 
    "username": { 
     type: "STRING", 
     length: 255 
    }, 
    "email": { 
     type: "EMAIL", 
     length: 255 
    } 
    }; 
}); 

app.directive('field', function($rootScope, $compile) { 
    return { 
    restrict: 'E', 
    scope: { 
     value: '=' 
    }, 
    link: function($scope, $element, $attrs) { 
     $scope.field_name = $attrs.name; 
     $scope.required = true; 
     console.log($scope); 
     var prepare_fields = function() { 
     if ($rootScope.meta) { 
      $scope.field = angular.copy($rootScope.meta[$attrs.name]); 
     } 

     var html = ''; 
     if ($scope.field.type === "STRING") { 
      html = '<input type="text" name="' +$scope.field_name+ '" ng-model="value[field_name]" ng-required="required" />'; 
     } else if ($scope.field.type === "EMAIL") { 
      html = '<input type="email" name="' +$scope.field_name+ '" ng-model="value[field_name]" ng-required="required" />'; 
     } 

     $element.html($compile(html)($scope)); 
     }; 

     $rootScope.$watch('meta', prepare_fields); 
    } 
    } 
}); 

回答

1

编译element.contents后添加的内容,所以只加波纹管两行

$element.html(html); 
$compile($element.contents())($scope); 

代替

$element.html($compile(html)($scope)); 

应在指令中工作:)

所以最终代码:

var html = ''; 
if ($scope.field.type === "STRING") { 
    html = '<input type="text" name="' +$scope.field_name+ '" ng-model="value[field_name]" ng-required="required" />'; 
} else if ($scope.field.type === "EMAIL") { 
    html = '<input type="email" name="' +$scope.field_name+ '" ng-model="value[field_name]" ng-required="required" />'; 
} 

// $element.html($compile(html)($scope)); 
$element.html(html); 
$compile($element.contents())($scope); 

NB:问题是你编一个element html。所以当编译元素内容修改后元素那么它的工作。

+0

太棒了!我完全错过了那部分:) – moustacheman