Pass form to directive

前端 未结 5 2118
盖世英雄少女心
盖世英雄少女心 2020-11-30 19:35

I want to encapsulate my form fields in a directive so I can simply do this:

5条回答
  •  一生所求
    2020-11-30 20:05

    Here a complete example (styled using Bootstrap 3.1)

    It contains a form with several inputs (name, email, age, and country). Name, email and age are directives. Country is a "regular" input.

    For each input is displayed an help message when the user does not enter a correct value.

    The form contains a save button which is disabled if the form contains at least one error.

    
    
      
      
      
      
    
      
    Person:
    {{person | json}}
    Form $error:
    {{myForm.$error | json}}

    Is the form valid?: {{myForm.$valid}}

    Is name valid?: {{myForm.name.$valid}}

    // inputName.js app.directive('inputName', function() { return { restrict: 'E', templateUrl: 'input-name.html', replace: false, controller: 'InputNameCtrl', require: ['^form', 'ngModel'], // See Isolating the Scope of a Directive http://docs.angularjs.org/guide/directive#isolating-the-scope-of-a-directive scope: {}, link: function(scope, element, attrs, ctrls) { scope.form = ctrls[0]; var ngModel = ctrls[1]; if (attrs.required !== undefined) { // If attribute required exists // ng-required takes a boolean scope.required = true; } scope.$watch('name', function() { ngModel.$setViewValue(scope.name); }); } }; }); // inputNameCtrl app.controller('InputNameCtrl', ['$scope', function($scope) { }]);

提交回复
热议问题